首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用来自两个不同角色的值来计算条件语句的出现情况

使用来自两个不同角色的值来计算条件语句的出现情况
EN

Stack Overflow用户
提问于 2020-02-10 15:21:07
回答 2查看 36关注 0票数 0

我有一个包含时间(UTC)和accountID字段的表。

代码语言:javascript
复制
accountID | time | ...
1         |12:00 |....
1         |12:01 |...
1         |13:00 |...
2         |14:00 |...

我需要进行一个sql查询,以返回一个新字段,该字段计数“accountID”,其中“类别”可以是“a”或“b”。如果来自同一accountID的行条目的正时差为1分钟或更短,则类别'a‘需要增加,否则'b’。上表的结果如下

代码语言:javascript
复制
accountID| cat a count| cat b count
1        | 1          | 2
2        | 0          | 1

我可以采取什么方法来比较不同行之间的值和比较结果的输出情况?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2020-02-10 15:34:30

要计算这个类别,您需要在“表表达式”中预先计算关闭行的结果。例如:

代码语言:javascript
复制
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

结果:

代码语言:javascript
复制
accountid  cat_a_count  cat_b_count
---------  -----------  -----------
1          1            2          
2          0            1          

作为参考,我使用的数据脚本是:

代码语言:javascript
复制
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');
票数 1
EN

Stack Overflow用户

发布于 2020-02-10 15:21:53

使用lag()和条件聚合:

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60153382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档