TSQL选择一对多。在Select语句中连接多对一列/行

时间:2017-08-09 13:39:06

标签: tsql select

我有一对一的select语句。

我希望来自Many的列中的结果显示为一行中的列。什么是最简单的方法。

表1

1   Joe   
2   Jill
3   Bill
4   Jennifer

表2

1    Red
1    Yellow
1    Blue
2    Green
2    Black
4    Purple

结果

1   Joe      Red, Yellow, Blue
2   Jill     Green, Black
3   Bill
4   Jennifer Purple

2 个答案:

答案 0 :(得分:0)

如果你有2017或Azure,那么string_agg()可用并使用它。如果没有,则显示for xml路径方法:

可能是你最好的选择。

但是你可以在Aaron的博客中看到:https://sqlperformance.com/2016/12/sql-performance/sql-server-v-next-string_agg-performance string_Agg()是可行的方法。

答案 1 :(得分:0)

如果您使用的是Sql server 2017或SQL Azure,则可以使用String_Agg,如下所示:

Select t1.Id, t1.Name, String_agg(color,',') from #table1 t1
left join #table2 t2 on t1.Id = t2.Id
Group by t1.Id, t1.Name

如果您使用的是SQL Server< = 2016,则可以使用以下查询:

Select t1.Id, t1.Name, Colors = stuff((select ','+color from #table2 tt2 where tt2.id = t1.id for xml path('')),1,1,'')
    From #table1 t1
Group by t1.Id, t1.Name

输出如下:

+----+----------+-----------------+
| Id |   Name   |     Colors      |
+----+----------+-----------------+
|  1 | Joe      | Red,Yellow,Blue |
|  2 | Jill     | Green,Black     |
|  3 | Bill     | NULL            |
|  4 | Jennifer | Purple          |
+----+----------+-----------------+
相关问题