配置单元:查找具有特定事件的唯一ID

chhkpiq4  于 2022-09-27  发布在  Hive
关注(0)|答案(2)|浏览(123)

我有一个包含ID和相关事件的配置单元表,如下所示。对于同一ID,该表可以有多个event_number-

ID    event_number    Date
ABC      1           2022-08-01
ABC      2           2022-08-01
ABC      3           2022-08-01
DEF      1           2022-08-01
GHI      2           2022-08-02
DEF      3           2022-08-01

我想找到一天内发生事件1和2的唯一ID

  • 这里的输出将是ABC,因为这是给定日期中同时包含事件1和事件2的唯一ID。
  • 它不能是DEF或GHI,因为它们有事件1或2

这是我为此提出的问题-

select distinct ID from table where event_number=1 and date=2022-08-01 
and ID in( Select ID from table where event_number=2 and date=2022-08-01);

有没有一种更优雅或更有效的方法来做到这一点?

uyto3xhc

uyto3xhc1#

首先对与事件筛选器匹配的记录进行筛选,然后在日期上进行聚合,得到给定日期的event_count大于1的行。例如

select id,`date`,count(distinct event_number) event_count from (
select id,event_number,`date` from table where id in (1,2)
) a group by id,`date` having event_count>1;
mspsb9vt

mspsb9vt2#

SQL如下:

select 
    id
from (
    select
        id,
        date,
        count(disintct event_number) as event_no_cnt
    from
        table 
    where
        event_number in (1,2)
    group by
        id,
        date
    having(count(disintct event_number)=2)
) tmp 
group by id

相关问题