SELECT
country_id,
partner,
retailer,
COUNT(id_clickout) AS clicks,
COUNT(DISTINCT CASE WHEN id_clickout IS NOT NULL THEN id_customer END) AS unique_clicks
FROM
test1
GROUP BY
1,2,3
;
COUNT(a_field)
won't count any NULL
values.
So, COUNT(id_clickout)
will only count the number of times that it is NOT NULL
.
Equally, the CASE WHEN
statement in the unique_clicks
only returns the id_customer
for records where they clicked, otherwise it returns NULL
. This means that the COUNT(DISTINCT CASE)
only counts distinct customers, and only when they clicked.
EDIT :
I just realised, it's potentially even simpler than that...
SELECT
country_id,
partner,
retailer,
COUNT(*) AS clicks,
COUNT(DISTINCT id_customer) AS unique_clicks
FROM
test1
WHERe
id_clickout IS NOT NULL
GROUP BY
1,2,3
;
The only material difference in the results will be that any country_id, partner, retailed
that previously showed up with 0 clicks
will now not appear in the results at all.
With an INDEX on country_id, partner, retailed, id_clickout, id_customer
or country_id, partner, retailed, id_customer, id_clickout
, however, this query should be significantly faster.