drop table if exists t;
create table t(id int, dt date, dummy int);
insert into t values
(1,'2018-01-31',1),(1,'2018-02-28',1),(1,'2018-03-31',1),
(2,'2018-01-31',0),(2,'2018-02-28',0),(2,'2018-03-31',1),
(3,'2018-01-31',1),(3,'2018-02-28',0),(3,'2018-03-31',1),
(4,'2018-01-31',0),(4,'2018-02-28',0),(4,'2018-03-31',0);
select s.id,sum(dummy) cnt
from
(
select t.*,
if (t.id <> @p,@r:=1,@r:=@r+1) r,
@p:=t.id p
from t
cross join (select @r:=0,@p:=0) rn
order by t.id,t.dt
) s
where s.r <= 2
group by s.id having cnt = 0;
+------+------+
| id | cnt |
+------+------+
| 2 | 0 |
| 4 | 0 |
+------+------+
2 rows in set (0.00 sec)
1条答案
按热度按时间xpcnnkqh1#
也许这是内部查询分配一个行号,外部查询计算出前两个月有多少未支付