首页 > 能不能用case...when...动态绑定group by列?

能不能用case...when...动态绑定group by列?

假设tableX如下:

Col1 Col2 Col3
a 1 1
a 2 2
b 1 1

那么

select col1 ,count(col2) as col2,sum(col3) as col3 from tableX group by col1 

输出

Col1 Col2 Col3
a 2 3
b 1 1
select count(col2) as col2,sum(col3) as col3 from tableX

输出

Col2 Col3
3 4

那么,能不能用一个使用case when 的查询同时实现以上两个语句,比如以下这种形式,当然,我下面贴的这个查询是运行不了的。
假设存储过程中,col1作为输入参数,但传了个空值进来。

select case when col1 is null then null else col1 end,count(col2) as col2,sum(col3) as col3 from tableX group by case when col1 is null then null else col1 end
【热门文章】
【热门文章】