gpt4 book ai didi

sql-server-2005 - 带汇总的 group by 子句

转载 作者:行者123 更新时间:2023-12-04 07:07:29 25 4
gpt4 key购买 nike

我正在尝试在 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

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

最佳答案

您不能在语句本身内执行此操作,但是您可以过滤 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), ())

关于sql-server-2005 - 带汇总的 group by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com