使用组合列和行的SQL生成报表?

使用组合列和行的SQL生成报表?,sql,sql-server,tsql,sql-server-2019,string-aggregation,Sql,Sql Server,Tsql,Sql Server 2019,String Aggregation,这是我的桌子: 表1采购报告 Purcu ID 客户ID 产品 数量 日期 1. 约翰 腿_01 2. 2021-04-09 2. 约翰 总目01 1. 2021-04-09 3. 黎明时分 总目01 1. 2021-04-09 4. 黎明时分 路肩_01 2. 2021-04-09 5. 黎明时分 腿_01 1. 2021-04-09 6. 基思 腿_01 2. 2021-04-09 您可以使用如下查询: SELECT Cust, STRING_AGG(Product + '_' + CA

这是我的桌子:

表1采购报告

Purcu ID 客户ID 产品 数量 日期 1. 约翰 腿_01 2. 2021-04-09 2. 约翰 总目01 1. 2021-04-09 3. 黎明时分 总目01 1. 2021-04-09 4. 黎明时分 路肩_01 2. 2021-04-09 5. 黎明时分 腿_01 1. 2021-04-09 6. 基思 腿_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\u 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]

第一列似乎基于最小的
purcu 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]

您使用的是哪种数据库管理系统?(答案可能是特定于产品的。)这可以通过MySQL.Sql express 2019中的group_concat完成。请参见
STRING_AGG()
您尝试了什么?你在哪里卡住了?让我们看看你的尝试。这太完美了。正是我需要的。谢谢大家的帮助。