将表格值作为逗号分隔列表返回到GROUP BY

时间:2015-06-30 14:09:57

标签: sql sql-server tsql

我希望从表中选择数据(SQL Server 2012) - 将一个字段分组并将该组中的所有重复项作为逗号分隔列表返回。

到目前为止我看到的所有解决方案都不允许组,并将整个表的单个逗号分隔列表作为变量返回,这对我不起作用。

我需要什么SQL?

这是我的数据:

BankingSlipID   CashSheetSessionID  BankingSlipNumber
1               10                  abcabc
2               10                  xyzxyz
3               10                  123465789
4               11                  9999999
5               11                  55555
6               12                  88888

这就是我想要的:

CashSheetSessionID  BankingSlipNumber
10                  abcabc, xyzxyz, 123465789
11                  9999999, 55555
12                  88888

创建源表的SQL(带数据):

CREATE TABLE [dbo].[BankingSlips](
[BankingSlipID] [int] IDENTITY(1,1) NOT NULL,
[CashSheetSessionID] [int] NOT NULL,
[BankingSlipNumber] [varchar](50) NOT NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[BankingSlips] ON
GO
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (1, 10, N'abcabc')
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (2, 10, N'xyzxyz')
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (3, 10, N'123465789')
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (4, 11, N'9999999')
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (5, 11, N'55555')
INSERT [dbo].[BankingSlips] ([BankingSlipID], [CashSheetSessionID], [BankingSlipNumber]) VALUES (6, 12, N'88888')
SET IDENTITY_INSERT [dbo].[BankingSlips] OFF
GO

我需要编写哪些SQL来获取它?

1 个答案:

答案 0 :(得分:1)

使用STUFF

SELECT CashSheetSessionID, BankingSlipNumber = 
    STUFF((SELECT ', ' + BankingSlipNumber
           FROM BankingSlips b 
           WHERE b.CashSheetSessionID = a.CashSheetSessionID 
          FOR XML PATH('')), 1, 2, '')
FROM BankingSlips a
GROUP BY CashSheetSessionID

输出:

CashSheetSessionID  BankingSlipNumber
10                  abcabc, xyzxyz, 123465789
11                  9999999, 55555
12                  88888

SQL小提琴:http://sqlfiddle.com/#!3/1d728b/4/0