Question

With help I recently received on SO, I managed to get data using the following snippet within my SELECT query:

COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 2 THEN 1 END) AS "2 day",

This produced the count of instances of an event of a particular condition being met.

But I would now like to calculate the number of people (Unique email addresses) associated with these events.

I tried this:

COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 2 THEN COUNT(DISTINCT TmpNIMSalesForceDB.EMAIL) END) AS "2 day"

The logic seems right in my mind - if the result of the case is 2 then count the distinct email addresses for that case.

But it seems SQL (Or Teradata) does not like nesting in this way. The resulting error message was "Cannot next aggregate function".

Can I use COUNT(DISTINCT in this way?

Was it helpful?

Solution

The expression that you want is a conditional count(distinct):

COUNT(DISTINCT CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 2
                    THEN TmpNIMSalesForceDB.EMAIL
               END) AS "2 day"

By leaving out the else clause, the value is NULL when the condition is not met. So, the distinct values of EMAIL are being counted for the condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top