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