我试图弄清楚如何向取决于特定行的累积添加额外条件。
我想做的是这样的:
select @datee := DATE_FORMAT(date, "%Y-%m") datee, count(distinct name) new
from requests where name not in (select name from requests where DATE_FORMAT(date, "%Y-%m") != @datee)
group by datee;
用文字表示:对于每个日期,它应该显示仅在该特定月份出现的名称数量。
结果可能如下所示:
datee new
2018-11 343 <-- all these names only occur in 2018-11
2018-12 384 <-- all these names only occur in 2018-12
2019-01 438 ...
2019-02 460 ...
2019-03 442
2019-04 463
2019-05 470
2019-06 290
谢谢你的帮助!
使用您的数据的简化版本,您可以检查该名称是否仅在一个月内出现并加入计数(不同)。
drop table if exists t;
create table t
(name varchar (1), mm int);
insert into t values
('a',1),('a',2),('a',3),
('b',2),
('c',1),('c',1),
('d',3),
('e',2),('e',2);
select mm,count(distinct t.name) obs
from t
join
(
select name, count(distinct mm) occurances
from
t
group by name having occurances = 1
) s on s.name = t.name
group by mm;
+------+-----+
| mm | obs |
+------+-----+
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
+------+-----+
3 rows in set (0.00 sec)
注意 a 完全消失,因为它出现在所有 3 个月内。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句