以下代码是否为每个月提取不同的数据。我的意思是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
答案 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