[英]dynamic grouping by in sql server
我想制作一个像makeGroupBy(@a int,@b int,@c int)
这样的存储过程。 输入是 0 或 1 来决定分组所依据的列。 到目前为止,我的尝试如下:
-- exec makeGroupBy 0,1,0
-- exec makeGroupBy 0,1,1
create proc makeGroupBy(@product_id int = 0,@city_id int = 1,@date_key
int = 0) as
begin
declare @tbl as table(product_id int, city_id int, date_key int, amount
float)
insert into @tbl
values(1,1,1,10),
(1,1,1,10),
(1,2,1,5),
(2,2,3,15),
(2,1,3,20),
(3,1,1,25)
select case isnull(@product_id,0) when 0 then 0 else product_id end
,case isnull(@city_id,0) when 0 then 0 else city_id end
,case isnull(@date_key,0) when 0 then 0 else date_key end
, sum(amount) amount from @tbl
group by case isnull(@product_id,0) when 0 then 0 else product_id end
,case isnull(@city_id,0) when 0 then 0 else city_id end
,case isnull(@date_key,0) when 0 then 0 else date_key end
end
我不知道是否有可能,但我想要的是省略结果集中不需要的列(值为 0 的输入)。
假设您的sql-server
版本大于或等于2008
。
select
product_id
,city_id
,date_key
,sum(amount) as total_amount
from @tbl
group by grouping sets (
(product_id, city_id, date_key)
, (product_id,city_id)
, (product_id, date_key)
, (city_id, date_key)
, (product_id)
, (city_id)
, (date_key))
having concat(iif(grouping_id(product_id)=0,1,0),iif(grouping_id(city_id)=0,1,0),iif(grouping_id(date_key)=0,1,0)) = concat(@product_id, @city_id, @date_key)
order by concat(iif(grouping_id(product_id)=0,1,0),iif(grouping_id(city_id)=0,1,0),iif(grouping_id(date_key)=0,1,0))
似乎view
可能最适合这种情况
create view [view_name]
as
select
product_id
,city_id
,date_key
,sum(amount) as amount
,concat(iif(grouping_id(product_id)=0,1,0),iif(grouping_id(city_id)=0,1,0),iif(grouping_id(date_key)=0,1,0)) as grp_key
from @tbl
group by grouping sets (
(product_id, city_id, date_key)
, (product_id,city_id)
, (product_id, date_key)
, (city_id, date_key)
, (product_id)
, (city_id)
, (date_key))
go
然后你可以像这样查询视图
select
city_id
,date_key
,amount
from [view_name]
where grp_key = concat(0,1,1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.