【问题标题】:Select identical values once in column and owned values in other column在列中选择相同的值一次,在其他列中选择拥有的值
【发布时间】:2014-02-27 22:11:37
【问题描述】:

我知道一开始标题没有意义。让我解释一下。

获得 3 张桌子:Reefers、Discipline 和 JudgedBy

在 Reefer 表中,我得到了 ID、姓名和姓氏。

---------------
1  John   Doe
2  john2  Doe2
3  etc

在 Discipline 表中,我得到了 Discipline 名称和 ID

------------
1   hockey
2   Basketball
3   football
4   etc

在 JudgedBy 表中,我从学科和冷藏表中获得了外键。有 Reefer id 和学科 id 。在一项运动项目中可以有多个冷藏箱

---------------
1  4  //Discipline with id 1 is judged by reefer with id 4,2,3 
1  2
1  3

我想要的是,在一列中选择学科(名称),在另一列中选择冷藏箱,这样学科只显示一次,所有冷藏箱都以字符串形式显示在行中。像这样的

---------
|hockey|      |John Doe , John2 Doe2, etc| 
|Basketball|  |Another reefer, Jet another reefer|

到目前为止,我已经完成了这项任务的两个部分,但我无法将它们放在一起。

为了选择学科和冷藏箱,我使用内部连接

SELECT  Discipline.Name, Reefers.name, Reefers.surname
FROM  Discipline INNER JOIN
      JudgedBy ON JudgedBy.Discipline_ID = Discipline.ID INNER JOIN
      Reefers ON JudgedBy.Reefer_ID = Reefers.ID

我明白了

------------
hockey   John Doe
hockey   John2 Doe2
hockey   Another one

另一部分是将它们放在一个字符串中。找到这件作品

declare @out as varchar(max)
set @out= ''
select @out = @out + Name + ' ' + Surnam + ', ' from Reefers
select @out as Game reefers 

我怎样才能把这两个部分放在一起?我希望我能解释一下我想要实现的目标。

谢谢!

【问题讨论】:

标签: sql sql-server database


【解决方案1】:

在 SQL Server 中进行聚合字符串连接有点痛苦。它需要一个子查询和for xml path()

这是您想要做的一个示例:

select d.name,
       stuff((select ', '+r.name + ' ' + r.surname
              from JudgedBy jb join
                   Reefers r
                   on jb.Reefer_ID = r.ID
              where jb.Discipline_ID = d.ID
              for xml path ('')
             ), 1, 2, '')
from Discipline d;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多