You need to change the aggregation function in your original query from COUNT
to SUM
:
SUM(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) -
CONTRACT_EFFECTIVE_DATE = 0 THEN DWELL_MINUTES END) AS "0 day"
Pregunta
I am using CASE WHEN in my select statement to count the number of records where a condition is true:
COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE)
- CONTRACT_EFFECTIVE_DATE = 1 THEN 1 END) AS "1 day",
That works fine.
Now I am attempting to apply the same condition but to sum the values in a column where it is true, rather than counting the records. Here is what I have tried:
(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE)
- CONTRACT_EFFECTIVE_DATE = 0 THEN SUM(DWELL_MINUTES) END) AS "0 day",
But that gave error "Selected non aggregate must be part of the associated group".
I tried some more variations with no success.
How would I sum the values contained in DWELL_MINUTES when CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 0
?
Solución
You need to change the aggregation function in your original query from COUNT
to SUM
:
SUM(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) -
CONTRACT_EFFECTIVE_DATE = 0 THEN DWELL_MINUTES END) AS "0 day"
Otros consejos
Do it the other way round, just like with COUNT. Do the evaluation per record and aggregate the results:
SUM(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE)
- CONTRACT_EFFECTIVE_DATE = 0 THEN DWELL_MINUTES END) AS "0 day",