Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 CASE Condition required in GROUP BY Clause?

Author  Topic 

Windza
Yak Posting Veteran

61 Posts

Posted - 2008-12-15 : 14:58:14
Just curious why a column reference in a CASE condition is required in the GROUP BY clause even though it isn't in the SELECT list (at least as an output)... is there an obvious explanation or standard workaround?
e.g.
SELECT

CASE WHEN column_name > 0
THEN column_name2 ELSE NULL END

FROM
table_name

GROUP BY
column_name2

fails with the standard msg:
Column 'column_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I understand the reasoning (I think anyway) behind the GROUP BY clause but cannot see why the above fails to work... the only way I can seem to bypass the issue is using something like the following:

SELECT
a.ColumnName2

FROM
(
SELECT
CASE WHEN column_name > 0
THEN column_name2 ELSE NULL END AS ColumnName2
FROM table_name
)a

GROUP BY
a.ColumnName2

If someone has stumbled across this before and has some answers I would be most appreciative... I realise I'm probably just posing a typical newbie type question but any information is valued nonetheless...
Cheers

hanbingl
Aged Yak Warrior

652 Posts

Posted - 2008-12-15 : 15:46:06
group by CASE WHEN column_name > 0
THEN column_name2 ELSE NULL END
Go to Top of Page

Windza
Yak Posting Veteran

61 Posts

Posted - 2008-12-15 : 16:06:03
Oh... that easy huh !

O O
*|*
\__/
Go to Top of Page
   

- Advertisement -