I have a requirement where I am getting data with Sql like below
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. The required output should be:
someid | passengertype | somename |
--------+----------------+-----------
111 | 4 | qwe |
111 | 6 | poi |
222 | 2 | lkj |
563 | 1 | uyt |
563 | 2 | mnb |
563 | 6 | oiu |
You can use not exists
. . . twice:
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
) ;
If you only wanted the someid
values that meet this condition, then aggregation would be appropriate:
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;
You can use the analytical function as 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
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.