问题描述
这是我的桌子:
餐桌购买报告
PURC_ID | CUS_ID | 产品 | 数量 | 日期 |
---|---|---|---|---|
1 | 约翰 | Leg_01 | 2 | 2021-04-09 |
2 | 约翰 | Head_01 | 1 | 2021-04-09 |
3 | 黎明 | Head_01 | 1 | 2021-04-09 |
4 | 黎明 | 肩_01 | 2 | 2021-04-09 |
5 | 黎明 | Leg_01 | 1 | 2021-04-09 |
6 | 基思 | Leg_01 | 2 | 2021-04-09 |
我想按如下方式构建报告:
表 4:(PURC 表将与其他列合并。我需要产品代码后跟下划线后跟数量)。
REP_ID | 客户 | PURC | 日期 |
---|---|---|---|
1 | 约翰 | 头_01_1,腿_01_2 | 2021-04-09 |
2 | 黎明 | 头_01_1,肩_01_2,腿_01_1 | 2021-04-09 |
3 | 基思 | Leg_01_2 | 2021-04-09 |
我知道如何连接表格,但我不确定如何以这种格式进行组合。非常感谢任何帮助。
解决方法
您可以使用这样的查询:
SELECT
Cust,STRING_AGG(Product + '_' + CAST(QTY AS varchar(10)),',') AS PURC,Date
FROM PURC_Table
GROUP BY Cust,Date
注意:STRING_AGG()
在 SQL Server 2017 及更高版本上受支持。
以下应该为您提供所需的输出
select row_number() over(order by avg(purc_id)) REP_ID,CUS_ID Cust,string_agg(product + '_' + cast(Qty as varchar(2)),') PURC,[Date]
from PurchaseReport
group by CUS_ID,[Date]
,
第一列似乎基于最小的 purc_id
。对于串联列,其他答案都很好,但 concat()
更方便:
select row_number() over (order by min(purc_id)) as rep_id
cus_id as Cust,string_agg(concat(product,'_',qty),') as purc,[Date]
from PurchaseReport
group by cus_id,[Date]