选择条件分组依据的列表 [英] Select List for a Conditional Group By

查看:104
本文介绍了选择条件分组依据的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我打算编写的SQL查询

Hi,

Here''s a SQL Query I intend to write

SELECT CASE COUNT(*) WHEN 1 THEN ColA ELSE MAX(ColA) END FROM tblMyTable GROUP BY CASE Cond1 WHEN 1 THEN ColB END




这是有条件的.当不应用分组依据时,我需要列A的值.如果将其分组,那么我想获得列A的最大值.


如预期的那样,这在选择列表中显示错误




It''s a conditional group by. When the group by is not applied, I need the column A''s value. And If it''s grouped then I want to the Max of Column A''s values.


As expected this shows the error

invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.



有什么建议吗?



Any suggestions?

推荐答案

我认为您将不得不使用动态SQL


I think you will have to use dynamic SQL


declare @strSql nvarchar(100)
declare @count int
select @count = COUNT(*) from tblMyTable where ID = 1
set @strSql ='select ' +
                case @count when 1 then ' ColA '
                else 'MAX(ColA)' end
+ 'from tblMyTable '
+ 'group by ' + case @count when 1 then  ' ColA '
                else ' ColB ' end

sp_executesql @strSql


这篇关于选择条件分组依据的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆