[英]SQL counting occurrences of conditional statements using values from 2 different roles
I have a table with fields including time (UTC) and accountID.我有一个包含时间 (UTC) 和 accountID 字段的表。
accountID | time | ...
1 |12:00 |....
1 |12:01 |...
1 |13:00 |...
2 |14:00 |...
I need to make an sql query to return the accountID with a new field counting 'category' where 'category' can be 'a' or 'b'.我需要进行 sql 查询以返回带有计数“类别”的新字段的 accountID,其中“类别”可以是“a”或“b”。 If there is a row entry from the same accountID that has a positive time difference of 1 minute or less, category 'a' needs to be incremented, otherwise 'b'.
如果来自同一 accountID 的行条目具有 1 分钟或更短的正时间差,则类别 'a' 需要递增,否则为 'b'。 The results from the above table would be
上表的结果将是
accountID| cat a count| cat b count
1 | 1 | 2
2 | 0 | 1
What approaches can I take to compare values between different rows and output occurrences of comparison outcomes?我可以采取哪些方法来比较不同行之间的值并输出比较结果的出现次数?
Thanks谢谢
To compute this categories you'll need to pre-compute the findings of close rows in a "table expression".要计算此类别,您需要预先计算“表表达式”中关闭行的结果。 For example:
例如:
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
Result:结果:
accountid cat_a_count cat_b_count
--------- ----------- -----------
1 1 2
2 0 1
For reference, the data script I used is:作为参考,我使用的数据脚本是:
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');
Use lag()
and conditional aggregation:使用
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.