我们正在运行SQL Server 2005.我在汇总列时遇到了问题。
create table group_roll
(
id_name int,
full_name varchar(50),
qty int
)
go
insert into group_roll (id_name, full_name, qty)
values (1, 'john smith', 10)
insert into group_roll (id_name, full_name, qty)
values (1, 'john smith', 40)
insert into group_roll (id_name, full_name, qty)
values (1, 'jane smith', 50)
insert into group_roll (id_name, full_name, qty)
values (1, 'dean smith', 10)
insert into group_roll (id_name, full_name, qty)
values (2, 'frank white', 5)
insert into group_roll (id_name, full_name, qty)
values (2, 'Ann white', 12)
insert into group_roll (id_name, full_name, qty)
values (1, 'john smith', 8)
insert into group_roll (id_name, full_name, qty)
values (2, 'frank white', 10)
insert into group_roll (id_name, full_name, qty)
values (3, 'perry mason', 10)
go
select *
from group_roll
order by id_name
输出:
id_name full_name qty
--------------------------------------
1 john smith 10
1 john smith 40
1 jane smith 50
1 dean smith 10
1 john smith 8
2 frank white 10
2 frank white 5
2 Ann white 12
3 perry mason 10
我希望将结果汇总成这样的内容
id_name name qty
----------------------------------------------------
1 john smith, jane smith, dean smith 118
2 frank white, ann white 27
3 perry mason 10
如何编码如图所示汇总名称和数量?
谢谢,
Seyed
答案 0 :(得分:1)
试试这个:它会给你你所期望的但你提供的输出,如果我没错,第三行持有错误值:
SELECT id_name,
STUFF((SELECT DISTINCT ', ' + full_name FROM group_roll A
WHERE A.id_name=b.id_name FOR XML PATH('')),1,1,'') As name,
SUM(qty) qty
FROM group_roll b
GROUP BY id_name