这似乎是一个简单的查询,但我正在努力解决它。
以下是我的数据样本。
user_id dated
463 2016-01-01
463 2016-01-02
1456 2016-01-01
1456 2016-01-02
1398 2015-12-01
1398 2015-12-02
我希望在两个不同的时间段内获得唯一身份用户的数量。以下是我想从单行和两列中获取组合输出的查询。
-- 60
SELECT COUNT(DISTINCT(tld.user_id)) count_active_users_60
FROM table tld
WHERE tld.dated BETWEEN (NOW() - INTERVAL '60 days') AND (NOW() - INTERVAL '30 days')
-- 30
SELECT COUNT(DISTINCT(tld.user_id)) count_active_users_30
FROM table tld
WHERE tld.dated >= NOW() - INTERVAL '30 days'
我想要一个看起来像这样的输出:
count_active_users_60 count_active_users_30
1 2
我一直在搞乱各种CASE语句和子选择,但是不同的条款让我失望。
SELECT COUNT(DISTINCT(rar.user_id))
FROM
(
SELECT user_id,
COUNT(CASE WHEN tld.dated BETWEEN (NOW() - INTERVAL '60 days') AND (NOW() - INTERVAL '30 days') THEN 1 ELSE NULL END) AS count_active_users_60,
COUNT(CASE WHEN tld.dated >= NOW() - INTERVAL '30 days' THEN 1 ELSE NULL END) AS count_active_users_30
FROM testing_login_duration tld
GROUP BY user_id
) rar;
答案 0 :(得分:3)
使用条件聚合:
SELECT COUNT(DISTINCT CASE WHEN tld.dated BETWEEN (NOW() - INTERVAL '60 days') AND (NOW() - INTERVAL '30 days')
THEN tld.user_id
END) count_active_users_60,
COUNT(DISTINCT CASE WHEN tld.dated >= NOW() - INTERVAL '30 days'
THEN tld.user_id
END) count_active_users_30
FROM table tld
WHERE tld.dated >= NOW() - INTERVAL '60 days';