2016-09-21 1 views
0

Nous exécutons SQL Server 2005. J'ai des problèmes à remonter des colonnes.Comment faire pour rollup colonnes

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 

Sortie:

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 

Je veux que le résultat soit enroulé dans quelque chose comme ça

id_name name         qty 
    ---------------------------------------------------- 
    1  john smith, jane smith, dean smith  118 
    2  frank white, ann white     27 
    3  perry mason        10 

Comment code comme indiqué Rollup noms et qté?

Merci,

Seyed

Répondre

1

Essayez ceci: Il vous donnera ce que vous attendiez, mais la sortie que vous avez fourni, si je ne me trompe pas la troisième ligne contenant une valeur incorrecte:

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 
+0

Cela a fonctionné. Merci beaucoup. Vous avez raison sur la troisième rangée, c'était le résultat d'une mauvaise copie et coller. Il devrait montrer 'Perry Mason'. – SeyedG

+0

Comment marquer ce message comme "Résolu" ou "Fermé" ou quelque chose du genre? – SeyedG