具有汇总的group by子句

时间:2011-06-18 13:03:00

标签: sql-server-2005 tsql group-by rollup

我正在尝试在sql server 2005中使用group by with 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

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

1 个答案:

答案 0 :(得分:3)

您不能在语句本身内执行此操作,但是您可以过滤除{6}之外的中间汇总的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), ())