每月提供不同用户的月度数据

时间:2018-04-11 08:19:54

标签: sql postgresql

以下代码是否为每个月提取不同的数据。我的意思是user_id在给定的月份中只能出现一次,但如果不在同一个月内会出现几次?

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

1 个答案:

答案 0 :(得分:0)

我认为您还需要添加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

作为变体,您可以使用to_char函数

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