我有 1 个包含 4 列的表格
id, name, key, date
1,'A' ,'x1','2015-11-11'
2,'A' ,'x1','2015-11-11'
3,'B' ,'x2','2015-11-11'
4,'B' ,'x2','2015-11-11'
5,'A' ,'x1','2015-11-12'
6,'A' ,'x1','2015-11-12'
7,'B' ,'x2','2015-11-12'
8,'B' ,'x2','2015-11-12'
9,'D' ,'x3','2015-11-12'
我想要按 [key] 和 [date] 进行分组。我想要的结果是:
2015-11-11 2
2015-11-12 1
2
:日期 2015-11-11 有 4 行(1,2,3,4)但有重复的键,因此当分组时我们只有 2 行。
1
:日期 2015-11-12 有 5 行 (5,6,7,8,9),但有 4 行 (5,6,7,8) 与日期 2015- 重复11-11,我不需要计算器 => 我们只有 1 行 (9)
我对我的英语感到抱歉。希望您能理解我的问题。
请以各种方式帮助我。我正在使用 mysql。
最佳答案
select key, date, (select count(*) from tablename t2
where t2.key = t1.key
and t2.date = t1.date
and not exists (select 1 from tablename t3
where t3.key = t2.key
and t3.date < t2.date))
from tablename t1
您可以使用相关子查询来计算该日期的键。如果已找到较旧日期的该日期的键值,则不进行计数。
替代解决方案:
select t1.key, t1.date, count(*)
from tablename t1
LEFT JOIN (select key, min(date) as date from tablename group by key) t2
ON t2.key = t1.key and t2.date = t1.date
group by t1.key, t1.date
关于mysql - 按2列分组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33730515/