我想将表的 primaryID 作为字符串与总和值连接起来。请看下面。
表结构
ID | Value
_______________
1 | 5000
_______________
2 | 6000
_______________
3 | 7000
_______________
4 | 9000
查询结果是我想要的
ALLID | ALLValue
___________________
1,2,3,4 | 27000
如何编写sql查询来产生更高的结果?谢谢大家。
最佳答案
在 SQL Server 中,对于字符串聚合,可以使用 XML 逻辑。以下是您的查询示例:
select stuff((select ',' + cast(id as varchar(255)
from structure s
for xml path ('')
), 1, 1, '') as AllId,
sum(value) as AllValue
from structure s;
请注意,外部查询是一个仅返回一行的聚合查询(因为 sum(value)
)。初始子查询与外部查询不相关,因此它将所有 id
组合成一个字符串。
关于sql-server - 将表主 ID 连接为具有总和值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27559098/