I am new to SQL.
I would like to use GROUP BY with a CASE statement to group the results in a specific way if @myboolean is true.
I have seen many examples of using GROUP BY and CASE BY with one field or how to use GROUP BY with multiple fields without a CASE statement.
I do not know how to combine these two. When I enclose GROUP BY fields in a CASE statement, I get a syntax error:
Invalid syntax near ','
So this works:
GROUP BY /* This works with no enclosing CASE statement */ field1, field2, field3, field4
This results in a syntax error:
GROUP BY CASE WHEN (@myboolean=1) THEN field1, <-- ERROR HERE: Incorrect syntax near ',' field2, field3, field4 ELSE field1 END
I have already addressed these issues:
SQL: Group By with Case Statement for multiple fields : it looks like GROUP BY based on CASE , and not on a group of several. In any case, there were no commas.
Group by multiple columns and case description : maybe I'm fat, but I don't see how this includes the case statement in GROUP BY
other less relevant
I am using Microsoft SQL Server Management Studio.
Note that I am inheriting a very complex / long SQL statement that I want to avoid too much. I do not want to split the query into two separate SELECT .
sql sql-server tsql
Lydia ralph
source share