繁体   English   中英

SQL 使用来自 2 个不同角色的值计算条件语句的出现次数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM