SQL query to find a specific value for all records

跟風遠走 提交于 2020-01-06 07:02:54

问题


Col1;Col2;Col3
12345;01;Y
12345;02;Y
12345;03;Y
22222;01;Y
22222;02;Y
22222;03;N
33333;01;N
44444;01;Y

Need help in writing a SQL query to find all the records with value = 'Y' based on col1.For Eg output select Col1 should give the output as 12345 and 44444 [ not 22222 and 33333 as the col3 contains 'N' for them ]

Thanks a lot for your time


回答1:


I guess you need col1 where all values of col3 should be Y

select col1
from demo
group by col1
having count(*) = sum(Col3 = 'Y')

Demo

Or if there can be only 2 possible values for col3 like Y/N then you can simplify your having clause as

having sum(Col3 = 'N') = 0

Demo




回答2:


One simple approach uses conditional aggregation:

SELECT Col1
FROM yourTable
GROUP BY Col1
HAVING MAX(Col3) = MIN(Col3) AND MAX(Col3) = 'Y';



回答3:


My solution:

select distinct col1
from mytable
where col3='Y'
and col1 not in (select distinct col1 from mytable where col3='N')



回答4:


my solution using the difference

select distinct col1 from demo where col1 not in 
(select col1 from demo where col3='N')


来源:https://stackoverflow.com/questions/50483770/sql-query-to-find-a-specific-value-for-all-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!