SQL Server在一行

时间:2017-07-04 13:59:56

标签: sql-server

我一直在尝试使用STUFF执行以下操作,但我想错了一些东西。

我有一个查询,它以

的形式返回连接表的结果
DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES
2017-02-01 | 12        | HAT
2017-02-01 | 12        | SHOES
2017-02-01 | 25        | GLOVES

我希望通过将ITEM_DESC组合成一行来减少这种情况:

DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES, HAT, SHOES
2017-02-01 | 25        | GLOVES

我正在尝试对返回的结果运行嵌套查询:

 select [Date] as PurDate, [client_ID], 
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, '' 
 ) 
from (select...

然而,它只是返回完全相同的结果。我需要对前两列进行分组,然后仅连接该组合的常用内容,但这就是我被卡住的地方。

1 个答案:

答案 0 :(得分:1)

你需要在下面添加group by,如下所示:

select [Date] as PurDate, [client_ID], 
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, '' 
 ) 
from (select...
) a
group by [Date], [Client_Id]

使用您的示例数据创建,您可以查询如下:

Select [Date], Client_id, 
    Stuff((Select ','+Item_desc from #alldata where [Date] = a.[Date] and [Client_id] = a.Client_id for xml path('')), 1,1,'')
    from #alldata a
    group by [Date], Client_id

输入表:

create table #alldata ([Date] date, Client_id int, Item_desc varchar(15))

insert into #alldata([date], Client_id, Item_desc) values
 ('2017-02-01', 12  ,'GLOVES')
,('2017-02-01', 12  ,'HAT')
,('2017-02-01', 12  ,'SHOES')
,('2017-02-01', 25  ,'GLOVES')

输出如下:

+------------+-----------+---------------------+
|    Date    | Client_id |      Item_Desc      |
+------------+-----------+---------------------+
| 2017-02-01 |        12 |  GLOVES, HAT, SHOES |
| 2017-02-01 |        25 |  GLOVES             |
+------------+-----------+---------------------+