具有逗号分隔值的

时间:2017-09-22 19:44:25

标签: sql-server

对于我的情况,我正在尝试应用stackoverflow解决方案here

以下是我的表格:

特长:

Id  Dish       ChefId
1   Caviar     1
2   Caviar     2
3   Foie gras  2
4   Foie gras  3
5   Foie gras  5
6   Truffles   1
7   Truffles   4

厨师:

Id  Name
1   Jake
2   Tara
3   Oscar
4   Linda
5   Wally

到目前为止,我想出了以下sql语句:

SELECT Dish, ChefId = 
    STUFF((SELECT ', ' + CONVERT(varchar(10), ChefId)
        FROM Specialty s1
        WHERE s1.Dish = s2.Dish
        FOR XML PATH('')), 1, 2, '')
    FROM Specialty s2
    GROUP BY Dish

结果:

Dish       Chef
Caviar     1, 2
Foie gras  2, 3, 5
Truffles   1, 4

但是,我想得到最终结果:

Dish       Chef
Caviar     Jake, Tara
Foie gras  Tara, Oscar, Wally
Truffles   Jake, Linda

2 个答案:

答案 0 :(得分:1)

您可以将查询与cte一起使用以加入名称:

;With Cte as (
    Select s.*, c.[Name] from #speciality S
    join #Chef c
    on s.ChefId = c.Id
) 
SELECT Dish, ChefNames = 
    STUFF((SELECT ', ' + [name]
        FROM Cte s1
        WHERE s1.Dish = s2.Dish
        FOR XML PATH('')), 1, 2, '')
    FROM Cte s2
    GROUP BY Dish

输出如下:

+-----------+--------------------+
|   Dish    |     ChefNames      |
+-----------+--------------------+
| Caviar    | Jake, Tara         |
| Foie gras | Tara, Oscar, Wally |
| Truffles  | Jake, Linda        |
+-----------+--------------------+

答案 1 :(得分:0)

你几乎就在那里,你所需要的只是INNER JOINSTUFF声明中的Chef表上,然后你只需用ChefId替换Name

SELECT Dish, ChefId = 
    STUFF((SELECT ', ' + c1.Name
        FROM Specialty s1
           INNER JOIN Chef c1
             ON s1.ChefId = c1.Id
        WHERE s1.Dish = s2.Dish
        FOR XML PATH('')), 1, 2, '')
    FROM Specialty s2
    GROUP BY Dish

我在这里有一个有效的SQL小提琴示例:http://www.sqlfiddle.com/#!6/9b7d5/6