[英]SQL counting occurrences of conditional statements using values from 2 different roles
我有一個包含時間 (UTC) 和 accountID 字段的表。
accountID | time | ...
1 |12:00 |....
1 |12:01 |...
1 |13:00 |...
2 |14:00 |...
我需要進行 sql 查詢以返回帶有計數“類別”的新字段的 accountID,其中“類別”可以是“a”或“b”。 如果來自同一 accountID 的行條目具有 1 分鍾或更短的正時間差,則類別 'a' 需要遞增,否則為 'b'。 上表的結果將是
accountID| cat a count| cat b count
1 | 1 | 2
2 | 0 | 1
我可以采取哪些方法來比較不同行之間的值並輸出比較結果的出現次數?
謝謝
要計算此類別,您需要預先計算“表表達式”中關閉行的結果。 例如:
select
accountid,
sum(case when cnt > 0 then 1 else 0 end) as cat_a_count,
sum(case when cnt = 0 then 1 else 0 end) as cat_b_count
from (
select
accountid, tim,
( select count(*)
from t b
where b.accountid = t.accountid
and b.tim <> t.tim
and b.tim between t.tim and addtime(t.tim, '00:01:00')
) as cnt
from t
) x
group by accountid
結果:
accountid cat_a_count cat_b_count
--------- ----------- -----------
1 1 2
2 0 1
作為參考,我使用的數據腳本是:
create table t (
accountid int,
tim time
);
insert into t (accountid, tim) values
(1, '12:00'),
(1, '12:01'),
(1, '13:00'),
(2, '14:00');
使用lag()
和條件聚合:
select accountid,
sum(prev_time >= time - interval 1 minute) as a_count,
sum(prev_time < time - interval 1 minute or prev_time is null) as b_count
from (select t.*,
lag(time) over (partition by accountid order by time) as prev_time
from t
) t
group by accountid;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.