Click here to Skip to main content
15,892,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Here's a SQL Query I intend to write

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



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?
Posted
Updated 16-Sep-11 3:47am
v2

1 solution

I think you will have to use dynamic SQL


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
 
Share this answer
 
v2
Comments
[no name] 19-Sep-11 1:33am    
Hi Sachin,

Thanks for your reply. Can you suggest an alternate solution, as this would return me an incorrect answer.

Right now the execution goes like this.


Q1*+ U Q2*

U - Union
* - Where conditions
+ - Group By

The first query (Q1) is grouped by and returns some values
The next query (Q2) returns by default 1 for all the remaining rows.

And combined, they have values for all rows.

I'm looking at combining both queries into one (Reason: Replicating where conditions with just minor change, Two Selects, One union all adds up to resource wastage)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900