我有一个包含时间(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我可以采取什么方法来比较不同行之间的值和比较结果的输出情况?
谢谢
发布于 2020-02-10 15:34:30
要计算这个类别,您需要在“表表达式”中预先计算关闭行的结果。例如:
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');发布于 2020-02-10 15:21:53
使用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;https://stackoverflow.com/questions/60153382
复制相似问题