[英]Filtering out the data grouping by id and some condition
我有一个使用 Sql 获取数据的要求,如下所示
someid | passengertype | somename |
--------+----------------+-----------
123 | 3 | abc |
123 | 6 | zxc |
111 | 4 | qwe |
111 | 6 | poi |
222 | 2 | lkj |
563 | 1 | uyt |
563 | 2 | mnb |
563 | 6 | oiu |
I want to select only records grouping by someid where passengertype not either 3 and 6. ie whenever for someid if passengertype contains only 3 or 6 then don't select that id, if 3 or 6 exists with other passengerid's then select. 所需的 output 应为:
someid | passengertype | somename |
--------+----------------+-----------
111 | 4 | qwe |
111 | 6 | poi |
222 | 2 | lkj |
563 | 1 | uyt |
563 | 2 | mnb |
563 | 6 | oiu |
你可以使用not exists
。 . . 两次:
select t.*
from t
where not exists (select 1
from t t2
where t2.someid = t.someid and t2.passengertype = 3
) or
not exists (select 1
from t t2
where t2.someid = t.someid and t2.passengertype = 6
) ;
如果您只想要满足此条件的someid
值,那么聚合将是合适的:
select someid
from t
group by someid
having sum(case when passengertype = 3 then 1 else 0 end) = 0 or
sum(case when passengertype = 6 then 1 else 0 end) = 0;
您可以使用分析 function 作为 dollows:
Select * from
(Select t.*,
Count(*) over (partition by id) as total_cnt,
Count(case when passenger_type in (3,6) then 1 end) over(partirion by id) as target_cnt
From your_table t) t
Where total_cnt != target_cnt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.