用sqlite计算列状态转换

时间:2018-09-21 12:36:05

标签: sql sqlite transition status

我需要计算每个代理的布尔列变为NO的次数。或每个代理从“是”转换为“否”的次数(以较容易为准) 示例:

Table Example

预期结果: agent_A,2 agent_B,0

1 个答案:

答案 0 :(得分:0)

基本上,您需要以前的值和累积和。 SQLite不支持窗口函数,因此这些技巧很棘手。

select t.*,
       (select t2.status
        from t t2
        where t2.agent = t.agent and t2.datescan < t.datescan
        order by t2.datescan desc
        limit 1
       ) as prev_status
from t;

接下来,您需要确定更改及其累积总和:

with tt as (
      select t.*,
             (select t2.status
              from t t2
              where t2.agent = t.agent and t2.datescan < t.datescan
              order by t2.datescan desc
              limit 1
             ) as prev_status
      from t
     )
select tt.*,
       (select count(*)
        from tt tt2
        where tt2.agent = tt.agent and tt2.datescan < t.datescan and
              tt2.status = 'NO' and tt2.prev_status = 'YES'
      ) as counter
from tt;