我有一个包含user_id和visited_at列的访问表。我想在本月找到有多少新客户和重复客户。
user_id visited_at
--------------------------------------------------------------------------
1750 2015-04-06 10:39:20
1870 2015-04-05 15:48:11
1990 2015-04-04 12:38:35
1920 2015-04-03 10:18:21
1080 2015-04-01 10:18:21
1750 2015-01-28 12:38:59
1920 2015-01-19 17:20:20
1920 2015-01-17 15:10:10
1080 2015-01-13 20:18:41
1920 2014-04-04 10:31:15
1750 2013-10-04 10:39:20
2015年1月,用户1750和1920访问了同一个地方,因此总重复客户数为2. 2015年4月,用户1750,1920和1080访问了同一个地方,因此总重复客户数为3.输出应该是这样的
Month New Repeat
----------------------------------------------
October 2013 1 0
April 2014 1 0
January 2015 1 2
April 2015 2 3
答案 0 :(得分:2)
一种方法是使用子查询获取每个用户的首次访问日期。然后加入此信息,并使用count(distinct)
计算用户数:
select year(v.visited_at) as yyyy, month(visited_at) as mm,
count(distinct user_id) as num_users,
count(case when v.visited_at = vv.minva then user_id end) as num_new_users
from visits v join
(select user_id, min(visited_at) as minva
from visits t
group by user_id
) vv
on v.user_id = vv.user_id
group by year(v.visited_at), month(visited_at)
order by year(v.visited_at), month(visited_at);
我注意到这给了全部和新用户;重复是不同的。
答案 1 :(得分:0)
这样的事情会起作用:
SELECT * FROM table_name WHERE updated_at >= CAST('2014-02-01' AS DATE) AND updated_at <= CAST('2014-02-28' AS DATE);
答案 2 :(得分:0)
SELECT
MONTH(created_at) as _Month,
YEAR(created_at) as _Year,
COUNT(*) as New
FROM
yourtable
GROUP BY 0,1
您还可以使用where子句过滤结果。