关注我之前的question。
我有一个名为activity
的表,有两列:
`when` as datetime // last time i saw a user
guid as varchar // a unique identifier for each user
我有一个查询,它返回给定日期和时间跨度的新用户数:
SET @till_date='2009-11-01'; #for today, give CURDATE()+1
SET @duration=1; # this can be changed to 7, 31, etc
SELECT COUNT(guid) AS total_new_users, DATE_SUB(@till_date, INTERVAL @duration DAY) AS since_date, @till_date AS till_date
FROM `activity` WHERE 1
AND `when` BETWEEN DATE_SUB(@till_date, INTERVAL @duration DAY) AND @till_date
AND guid NOT IN
(
SELECT guid
FROM `activity`
WHERE `when` < DATE_SUB(@till_date, INTERVAL @duration DAY)
)
我希望能够构建一个查询,该查询将在给定的时间跨度内返回每个日期的新用户列表。它将用于构建一个月,一周等每天新用户的图表。
这样的事情:
total_new_users | since_date | till_date
----------------------------------------------
10 | 2009-11-20 | 2009-11-21
10 | 2009-11-21 | 2009-11-22
10 | 2009-11-22 | 2009-11-23
我考虑过将UNION
与LOOP
一起使用,但我的SQL知识非常基础,有帮助吗?
结果(感谢@pilcrow):
SET @till_date='2009-11-15';
SET @since_date='2009-11-01';
SELECT first AS yyyymmdd,
COUNT('x') AS new_user_count
FROM (SELECT guid,
DATE(MIN(`when`)) AS first
FROM activity
GROUP BY 1) first_appearance
WHERE first BETWEEN @since_date AND @till_date
GROUP BY 1
答案 0 :(得分:2)
假设 SET SESSION sql_mode ='ANSI_QUOTES':
SELECT first AS yyyymmdd,
COUNT('x') AS new_user_count
FROM (SELECT guid,
MIN("when") AS first
FROM activity
GROUP BY 1) first_appearance
WHERE first BETWEEN @since_date AND @till_date
GROUP BY 1
如果您愿意,您当然可以将DATE_SUB()
替换为@since_date
。
答案 1 :(得分:0)
SELECT
COUNT(DISTINCT guid) AS total_new_users,
DATE(when) AS since_date,
DATE(DATE_ADD(when, INTERVAL 1 DAY)) AS till_date
FROM
Activity
GROUP BY
DATE(when)