本文介绍了选择条件分组依据的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我打算编写的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
更多推荐
选择条件分组依据的列表
发布评论