在SQL Server中动态分组

时间:2019-03-14 18:09:27

标签: sql sql-server stored-procedures

我想创建一个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的输入)。

1 个答案:

答案 0 :(得分:1)

假设您的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)