Arno Visser
Arno Visser

Reputation: 75

MySQL SELECT SUM CASE with GROUP BY or DISTINCT

I'm trying to count unique user ids in a log table by month. So far I came up with the following query:

SELECT 
COUNT(CASE WHEN log_date LIKE '2020-01%' THEN 1 END) AS januari
FROM user_log;

This query returns the total of all rows of the user_log in januari. However I would like to know how many unique users have logged in in Januari. So I need something like:

SELECT 
COUNT(**DISTINCT user_id** CASE WHEN log_date LIKE '2020-01%' THEN 1 END) AS januari
FROM user_log;

I also tried GROUP BY, but so far no luck. Does anyone have a suggestion?

Upvotes: 0

Views: 227

Answers (1)

GMB
GMB

Reputation: 222572

Consider:

SELECT COUNT(DISTINCT CASE WHEN log_date >= '2020-01-01' AND log_date < '2020-02-01' THEN userid END) AS januari
FROM user_log;

I changed the filtering logic to use half-open intervals rather than string matching: it is more efficient.

Note that, if you just that result for January, it is sufficient to use a WHERE clause:

SELECT COUNT(DISTINCT userid) januari
FROM user_log
WHERE log_date >= '2020-01-01' AND log_date < '2020-02-01'

Upvotes: 2

Related Questions