如何汇总列

How to rollup columns

我们是 运行 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

您如何编码以如图所示汇总名称和数量?

谢谢,

赛义德

试试这个:它会给你你所期望的但你提供的输出,如果我没记错第三行持有错误的值:

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