Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using case with aggregate function & group by clauses

I have a query using CASE with aggregate function and group by clause, like this

SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL 
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C
,<ALIAS>

and I got an error "GROUP BY and WITH...BY clauses may not contain aggregate"

then, I change my script (exclude from group by)

SELECT
A
,B
,C
,CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL 
     THEN (SUM(<COLUMN_NAME_B>) * <COLUMN_NAME_A>)
          ELSE 0
END AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C

and still got an error "Selected non-aggregate values must be part of the associated group"

please help me to understand why must be part of group by, and what do I have to do to fix it?

like image 858
galeka Avatar asked Dec 01 '22 22:12

galeka


1 Answers

Try this:

SELECT
A
,B
,C
,SUM(CASE
     WHEN <COLUMN_NAME_A> IS NOT NULL 
     THEN <COLUMN_NAME_B> * <COLUMN_NAME_A>
          ELSE 0
END) AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C

But your CASE statement have no sense. If <COLUMN_NAME_A> is NULL i.e. <COLUMN_NAME_B> * <COLUMN_NAME_A> is NULL it will be ignored by SUM aggregate. Use this instead.

SELECT
A
,B
,C
,ISNULL(SUM(<COLUMN_NAME_B> * <COLUMN_NAME_A>), 0) AS <ALIAS>
FROM <TARGET_TABLE>
GROUP BY
A
,B
,C

ISNULL used in case when no non-null value retrieved.

like image 147
Hamlet Hakobyan Avatar answered Dec 05 '22 12:12

Hamlet Hakobyan