计算某些预定义数据的行数

时间:2014-03-21 14:16:49

标签: php mysql sql count

我有一个数据集:

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的当前labelB 例如我想有以下输出:

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

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;