我有一个如下所示的订单表,其中每个订单组的每个订单记录都放在一行上。现在我想通过将一个组的所有订单放在一个单元格中并用“,”(结果表位于原始表下方)来分组,并按组聚合数据。
您能告诉我如何在SQL中实现这一点吗?
非常感谢!
这是原始表格:
Group Order
1 a
1 b
1 c
2 d
2 e
3 f
这是转换后的紧凑表:
Group Orders
1 a,b,c
2 d,e
3 f
答案 0 :(得分:3)
这将有助于
T-Sql(Sql Server 2005 +)
Declare @t Table([Group] Int, [Order] Varchar(20))
Insert Into @t Values(1,'a'),(1,'b'),(1,'c'),(2,'d'),(2,'e'),(3,'f')
Select [Group],
Orders = Stuff((Select ',' + Cast([Order] As Varchar(100))
From @t t2 Where t2.[Group] = t1.[Group]
For Xml Path('')),1,1,'')
From @t t1
Group By t1.[Group]
Pl / Sql Oracle 11g R2 +
SELECT [Group],ListAgg([Order],',') Within Group (Order By [Group]) Orders
FROM ORDER
GROUP BY [Group];
Pl / Sql Oracle 10g +
SELECT [Group],WM_Concat([Order],',') Orders
FROM ORDER
GROUP BY [Group];