需要计算每天添加的用户数量,给定日期和日期的日期范围,例如如下所示:
select
'2017-06-01' as myDate
, count(distinct user_id)
from tbl_stats
where date(dateTime)<='2017-06-01'
union all
select
'2017-06-02' as myDate
, count(distinct user_id)
from tbl_stats
where date(dateTime)<='2017-06-02'
输出如下:
reportDate | count
------------+-------
2017-06-01 | 2467
2017-06-02 | 2470
所以,我将只有fromDate和toDate,我需要在表中明确区分不同的用户数。我不会使用任何程序或循环。
答案 0 :(得分:1)
SELECT DATE(ts.dateTime) AS reportDate
, COUNT(distinct ts.user_id) AS userCount
FROM tbl_stats AS ts
WHERE ts.dateTime >= @lowerBoundDate
AND ts.dateTime < TIMESTAMPADD('DAY', 1, @upperBoundDate)
GROUP BY DATE(ts.dateTime)
答案 1 :(得分:0)
要获得每天累计(不同)用户数,请使用以下内容,将以下示例中给出的自定义日期替换为开始日期和结束日期。
WITH test_data AS (
SELECT '2017-01-01'::date as event_date, 1::int as user_id
UNION
SELECT '2017-01-01'::date as event_date, 2::int as user_id
UNION
SELECT '2017-01-02'::date as event_date, 1::int as user_id
UNION
SELECT '2017-01-02'::date as event_date, 2::int as user_id
UNION
SELECT '2017-01-02'::date as event_date, 3::int as user_id
UNION
SELECT '2017-01-03'::date as event_date, 4::int as user_id
UNION
SELECT '2017-01-03'::date as event_date, 5::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 1::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 2::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 3::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 4::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 5::int as user_id
UNION
SELECT '2017-01-04'::date as event_date, 6::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 3::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 4::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 5::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 6::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 7::int as user_id
UNION
SELECT '2017-01-05'::date as event_date, 8::int as user_id
UNION
SELECT '2017-01-06'::date as event_date, 7::int as user_id
UNION
SELECT '2017-01-06'::date as event_date, 9::int as user_id
)
SELECT event_date,
COUNT(distinct user_id) AS distinct_user_per_day,
SUM(COUNT(distinct user_id)) OVER (ORDER BY event_date) AS cumulative_user_count
FROM test_data
WHERE event_date >= '2017-01-01'
AND
event_date <= '2017-01-06'
GROUP BY
event_date