2011-06-18 351 views
3

我想在sql server 2005中使用group by和rollup子句,但我遇到了一些问题。group by by rollup

这是一个简单的转储

create table group_roll (
id int identity, 
id_name int, 
fname varchar(50), 
surname varchar(50), 
qty int 
) 

go 
insert into group_roll (id_name,fname,surname,qty) values (1,'john','smith',10) 
insert into group_roll (id_name,fname,surname,qty) values (1,'john','smith',30) 
insert into group_roll (id_name,fname,surname,qty) values (2,'frank','white',5) 
insert into group_roll (id_name,fname,surname,qty) values (1,'john','smith',8) 
insert into group_roll (id_name,fname,surname,qty) values (2,'frank','white',10) 
insert into group_roll (id_name,fname,surname,qty) values (3,'rick','black',10) 
go 

如果我运行这个简单的查询

select id_name,fname,surname,sum(qty) as tot 
from group_roll 
group by id_name,fname,surname 

我得到

1 john smith 48 
2 frank white 15 
3 rick black 10 

我想有

1 john smith 48 
2 frank white 15 
3 rick black 10 
Total    73 

这是我一直在努力,达到我的目标

select 
case when grouping(id_name) = 1 then 'My total' else cast(id_name as char) end as Name_id , 
fname,surname,sum(qty) as tot 
from group_roll 
group by id_name,fname,surname 
with rollup 
order by case when id_name is null then 1 else 0 end, tot desc 

,但我的结果是

1        john smith 48 
1        john NULL 48 
1        NULL NULL 48 
2        frank white 15 
2        frank NULL 15 
2        NULL NULL 15 
3        rick black 10 
3        rick NULL 10 
3        NULL NULL 10 
My total       NULL NULL 73 

哪里是我的错?

编辑。 我能解决我的问题作出

select * from (
select cast(id_name as char) as id_name,fname,surname,sum(qty) as tot 
from group_roll 
group by id_name,fname,surname 
union 
select 'Total',null,null,sum(qty) from group_roll) as t 
order by case when id_name = 'Total' then 1 else 0 end,tot desc 

,但我想了解是否可以汇总解决我的问题。

+0

我对我的方式出了门,并且还为时过早上周六,我想清楚了,但也许试图通过FNAME +姓分组,而不是两个单独的字段+1 – jlnorsworthy

回答

3

不能语句本身内做到这一点,但你可以过滤ROLLUP集不包括中间汇总,即其中的任何一个,但不是所有的行进行分组:

select 
    case when grouping(id_name) = 1 then 'My total' else cast(id_name as char) end as Name_id, 
    fname, 
    surname, 
    sum(qty) as tot 
from group_roll 
group by id_name, fname, surname 
with rollup 
having grouping(id_name) + grouping(fname) + grouping(surname) in (0 , 3) 

或类似的解决方案,但引用原始查询;

;with T as (
    select cast(id_name as varchar(128)) as id_name,fname,surname,sum(qty) as tot 
    from group_roll 
    group by id_name,fname,surname 
) select * from T union all select 'Total:',null,null, SUM(tot) from T 

FWIW SQL 2008允许;

select 
    case when grouping(id_name) = 1 then 'My total' else cast(id_name as char) end as Name_id, 
    fname, 
    surname, 
    sum(qty) as tot 
from group_roll 
group by grouping sets((id_name, fname, surname),()) 
+0

。嗨,亚历克斯。非常感谢你为这个伟大的答案。 ;) –