简体   繁体   中英

dynamic grouping by in sql server

i want to make a stored procedure like makeGroupBy(@a int,@b int,@c int) . The inputs are 0 or 1 to decide which columns to group by. My attempt so far is below:

-- 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

I don't know if it's possible but what I want is to omit the unwanted columns (inputs with value 0) in the result set.

Assuming that your sql-server version is greater or equal than 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))

It seems that a view will probably suit best for this case

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

Then you can query the view like

select 
    city_id
    ,date_key
    ,amount
from [view_name]
where grp_key = concat(0,1,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM