我有一个数据集:
id label date
1 B 2014-02-15
1 NB 2014-02-16
1 B 2014-02-17
1 B 2014-02-18
我想count(id)
如果前一个id
的当前label
为B
例如我想有以下输出:
label count(id)
B 1
NB 1
到目前为止,我已尝试过以下查询:
select a.label,count(a.id)
from test a
WHERE a.date <(select max(b.date) from test b
where b.label= 'B'
)
group by 1
答案 0 :(得分:1)
您需要获取以前的标签。我会使用相关子查询执行此操作,然后执行聚合:
select label, count(*)
from (select t.*,
(select t2.label
from test t2
where t2.date < t.date
order by t2.date desc
limit 1
) as prevlabel
from test t
) t
where prevlabel = 'B'
group by label;