使用 sqlite 计算列状态转换
Count column status transition with sqlite
我需要计算每个代理的布尔列更改为“否”的次数。或者每个代理有多少次从“是”过渡到“否”(以更容易的为准)
示例:
预期结果:
agent_A, 2
agent_B, 0
基本上,你需要前值和累计总和。 SQLite 不支持 window 函数,所以这些函数很棘手。
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;
我需要计算每个代理的布尔列更改为“否”的次数。或者每个代理有多少次从“是”过渡到“否”(以更容易的为准) 示例:
预期结果: agent_A, 2 agent_B, 0
基本上,你需要前值和累计总和。 SQLite 不支持 window 函数,所以这些函数很棘手。
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;