表a如下
订单号 方式
a 1543
a 3452
a 1333
a 7210
b 5611
b 4244
c 7210
c 8888
c 9999
我想得出大于2种方式且包含7210方式的订单号是哪些
sql怎么写,请教了
select * from a
where 订单号 in
(
select
订单号
from(
select
订单号,
count(方式)as 数量
from a
group by 订单号) aa
where 数量>2
) and 方式=7210
这么写对吧
我觉得直接分区count应该能拿到每个分组的数量然后外层按照方式和数量过滤,只套两层
select * from
(select * , count(方式) over(partition by 方式) as n from table ) tem where 方式=7120 and n > 2
差不多,不过我会选择先过滤数据再进行聚合
select a.订单号 from a,(select 订单号 from a where 方式=7210) b where a.订单号=b.订单号 group by a.订单号 having count(1)>2
另外,我看你这个sql最后还是想查对应订单的原始记录?
hive是支持开窗函数的,用下面这个方式,套的层数更少,而且只用查询一次原表
select t2.id,t2.tp from (
select t.*,
count(1)over(partition by id) ct,
count(case when tp=7210 then 1 end) over(partition by id) c7210
from test_20220218 t) as t2
where ct>2 and c7210=1
废话不多说了,唉,上面的答案我看了都头疼
select id,count(1)
from
table a,
table b
where
a.id = b.id
and b.type = '7210'
group by
a.id
having count(1) > 1
;