简体   繁体   中英

extract monthly data with distinct user per month

Does the following code extract distinct data for each month. I mean a user_id can be only one time in a given month but be appear several time if it is not in the same month?

SELECT COUNT(DISTINCT user_id), EXTRACT (MONTH FROM created_at) MTH
FROM user_logins
WHERE created_at >= '2017-01-01' AND
created_at <= '2018-04-10' 
GROUP BY EXTRACT (MONTH FROM created_at)
ORDER BY MTH ASC

I think you also need to add Year

SELECT
  COUNT(DISTINCT user_id),
  EXTRACT(YEAR FROM created_at) Y,
  EXTRACT(MONTH FROM created_at) M
FROM user_logins
WHERE created_at >= '2017-01-01'
  AND created_at <= '2018-04-10' 
GROUP BY EXTRACT(YEAR FROM created_at),EXTRACT(MONTH FROM created_at)
ORDER BY Y,M

And as variant you can use to_char function

SELECT
  COUNT(DISTINCT user_id),
  to_char(created_at, 'YYYY-MM') YM
FROM user_logins
WHERE created_at >= '2017-01-01'
  AND created_at <= '2018-04-10' 
GROUP BY to_char(created_at, 'YYYY-MM')
ORDER BY YM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM