繁体   English   中英

如何将多行汇总为单行和单列

[英]How to roll up multiple rows into a single row and column

我引用了这个和其他堆栈

这就是我所做的:

SELECT 
    ReportDate,  
    ReportID = STUFF((SELECT ',' + CAST(t1.ReportID AS varchar(50)) 
                      FROM BackEndEfficiency t1
                      WHERE t1.ReportID = t2.ReportID
                      FOR XML PATH ('')), 1, 1, '') 
FROM
    BackEndEfficiency t2
GROUP BY
    ReportDate

错误:

列“BackEndEfficiency.ReportID”在选择列表中无效,因为它既不包含在聚合函数中也不包含在 GROUP BY 子句中。

为什么我会收到此错误,因为我希望ReportDate被分组?

数据结构示例

ReportDate  ReportID
--------------------
2020-03-11  30
2020-03-11  31
2020-03-16  32
2020-03-16  33

我想得到这个输出:

ReportDate  ReportID
--------------------
2020-03-11  30,31
2020-03-16  32,33

我认为您需要ReportDate作为相关条款。 我会推荐:

select bee.ReportDate,
       stuff((select ',' + CAST(t1.ReportID as varchar(50)) 
              from BackEndEfficiency bee2
              where bee2.ReportDate = bee.ReportDate
              for xml path ('')
             ), 1, 1, '') 
from (select bee.ReportDate
      from BackEndEfficiency bee
     ) bee;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM