简体   繁体   中英

SQL counting occurrences of conditional statements using values from 2 different roles

I have a table with fields including time (UTC) and 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'. 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'. 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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