Mysql 如何根据前几行的数据对表进行分组并获取行的结果
我有一个查找表,用于关联日期和与这些日期关联的人员:Mysql 如何根据前几行的数据对表进行分组并获取行的结果,mysql,sql,Mysql,Sql,我有一个查找表,用于关联日期和与这些日期关联的人员: id, user_id,date 1,1,2014-11-01 2,2,2014-11-01 3,1,2014-11-02 4,3,2014-11-02 5,1,2014-11-03 我可以按日期将其分组: SELECT DATE_FORMAT( MIN(date), '%Y/%m/%d 00:00:00 GMT-0' ) AS date,
id, user_id,date
1,1,2014-11-01
2,2,2014-11-01
3,1,2014-11-02
4,3,2014-11-02
5,1,2014-11-03
我可以按日期将其分组:
SELECT DATE_FORMAT(
MIN(date),
'%Y/%m/%d 00:00:00 GMT-0'
) AS date,
COUNT(*) as count
FROM user_x_date
GROUP BY ROUND(UNIX_TIMESTAMP(created_at) / 43200)
但是,如何获得以前显示过的唯一用户的数量呢?例如,这将是一个有效的结果:
unique, non-unique, date
2,0,2014-11-01
1,1,2014-11-02
0,1,2014-11-03
这可能不需要依赖脚本语言来跟踪这些数据吗?我认为这个查询可以满足您的需要,至少它似乎可以为您有限的样本数据工作 其思想是使用相关子查询检查用户id是否出现在当前行日期之前的某个日期,然后执行一些基本算法来确定每个日期的唯一/非唯一用户数 请试一试
select
sum(u) - sum(n) as "unique",
sum(n) as "non-unique",
date
from (
select
date,
count(user_id) u,
case when exists (
select 1
from Table1 i
where i.user_id = o.user_id
and i.date < o.date
) then 1 else 0
end n
from Table1 o
group by date, user_id
) q
group by date
order by date;
我没有将id列包含在示例fiddle中,因为它不需要或不用于生成结果,也不会改变任何内容。这是一个相关的问题:但是,如何获得以前显示的唯一用户的数量 计算人员第一次出现的时间,然后将其用于聚合:
SELECT date, count(*) as FirstVisit
FROM (SELECT user_id, MIN(date) as date
FROM user_x_date
GROUP BY user_id
) x
GROUP BY date;
SELECT v.date, v.NumVisits, COALESCE(fv.FirstVisit, 0) as NumFirstVisit
FROM (SELECT date, count(*) as NumVisits
FROM user_x_date
GROUP BY date
) v LEFT JOIN
(SELECT date, count(*) as FirstVisit
FROM (SELECT user_id, MIN(date) as date
FROM user_x_date
GROUP BY user_id
) x
GROUP BY date
) fv
ON v.date = fv.date;
然后,我会将其用作另一个聚合的子查询:
SELECT date, count(*) as FirstVisit
FROM (SELECT user_id, MIN(date) as date
FROM user_x_date
GROUP BY user_id
) x
GROUP BY date;
SELECT v.date, v.NumVisits, COALESCE(fv.FirstVisit, 0) as NumFirstVisit
FROM (SELECT date, count(*) as NumVisits
FROM user_x_date
GROUP BY date
) v LEFT JOIN
(SELECT date, count(*) as FirstVisit
FROM (SELECT user_id, MIN(date) as date
FROM user_x_date
GROUP BY user_id
) x
GROUP BY date
) fv
ON v.date = fv.date;