sql - 如何将多行汇总成单行和单列
问题描述
我引用了这个和其他堆栈
这就是我所做的:
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
解决方案
I think you want ReportDate
for the correlation clause. I would recommend:
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;
推荐阅读
- django - django cache_page 如何过期?
- ruby-on-rails - 定位新的 postgres 数据库 (rails)
- python-3.x - 试图从父类继承变量“NameError: name 'r' is not defined”
- excel - 如何按索引位置返回数组中的元素值?
- arrays - 将 1,2 字符串转换为数组 [1, 2]
- ios - 使用 iOS 设置 TCP_QUICKACK
- php - 如何使用Jquery从输入类型=文件中的mysql数据库传递一个值?
- python - Python - POST 请求时拒绝访问 403
- xml - xslt 2.0:无法从 xml 中选择多个值
- r - 如何绕过使用不同日期的重复函数?