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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With