首页 > 解决方案 > 仅连接该组的更新列

问题描述

我必须在某个日期之前连接每个客户购买的商品

现在的情景

Date   CustomerID ItemID PreviousItems
9/9/19 C1         I1     NULL
8/8/19 C1         I2     NULL
7/7/19 C1         I3     NULL
6/6/19 C1         I4     NULL
9/9/19 C2         I5     NULL
8/8/19 C2         I1     NULL
7/7/19 C2         I4     NULL

期望的输出

Date   CustomerID ItemID PreviousItems
9/9/19 C1         I1     I2,I3,I4
8/8/19 C1         I2     I3,I4
7/7/19 C1         I3     I4
6/6/19 C1         I4     NULL
9/9/19 C2         I5     I1,I4
8/8/19 C2         I1     I4
7/7/19 C2         I4     NULL

我试过这段代码但没有用

因为我不知道在哪里按客户 ID 分组!

update a
  set PreviousItems = COALESCE(PreviousItems+ ', ', '') + ItemID 
from Purchase a

如何使用 group by 更新?

标签: sqlsql-serversql-updatesql-server-2014

解决方案


您可以通过考虑辅助查询中的方法来使用表INNER JOINUPDATE [PreviousItems]列:FOR XML

update t
    set t.[PreviousItems]=right(q.data,len(q.data)-1)
   from tab as t
   join (
select t1.[Date], t1.[CustomerID],
       stuff((select distinct ',' + t2.[ItemID]
                from tab t2
               where t2.[Date]<t1.[Date]
                 and t1.[CustomerID] = t2.[CustomerID]  for xml path(''), type
             ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') data
  from tab t1
 group by t1.[CustomerID], t1.[Date]
) q on  t.[Date]=q.[Date] and t.[CustomerID]=q.[CustomerID];

Demo


推荐阅读