sql - 仅连接该组的更新列
问题描述
我必须在某个日期之前连接每个客户购买的商品
现在的情景
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 更新?
解决方案
您可以通过考虑辅助查询中的方法来使用表INNER JOIN
的UPDATE
[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];
推荐阅读
- c# - 在 Godaddy 上部署 Asp Net Core 2.2 网站后出现错误 403
- javascript - 即使结果正确,函数也不会在 ref.on() 中响应
- highcharts - 在没有日期的 Highcharts 中使用 RangeSelector
- java - 带有 Ashot 问题的 Chrome 移动仿真屏幕截图
- android - 无法使用 android.arch.lifecycle:extensions 和 com.android.support:preference
- merge - 如何重新组合master上的一些旧提交?
- wix - 如何使用安装包 (msi) 中刻录 UI 中设置的选项
- c# - C#:释放内存使用
- python - BeautifulSoup 获取字符串之间的链接
- google-app-maker - google-app-maker - App Maker 将很快弃用外键字段。我们建议您改用关系