Question:
How to filter rows based on multiple conditions in sql?
Chris
2011-03-17 17:21:59 UTC
I have 2 columns in a table ID and name

ID Name
1 A
1 B
1 C
2 B
2 C
3 A
3 B

I want the result set as if the value A is present then only that row should be shown, if not all the other values should be shown.
Result

1 A
2 B
2 C
3 A
Four answers:
anonymous
2011-03-17 17:55:41 UTC
Try this:



select distinct ID, Name

from YourTable

where Name='A'

UNION

select distinct a.id, a.name

from YourTable a

left join YourTable b on a.id = b.id and b.name='A'

where b.id is null

order by id, name



Enjoy :)
?
2016-11-16 17:51:03 UTC
you somewhat should not be doing this style of string manipulation in sq. itself. that is larger to do this style of ingredient interior the shopper code (for courses). yet once you want a speedy and grimy answer each and each version of sq. has some thing which will do the trick. that's an answer for MSSQL. declare @chvResult NVARCHAR(MAX) go with @chvResult = ISNULL(@chvResult + ', ' + chvValue, chvValue) FROM dbo.tb_Table go with @chvResult
TheMadProfessor
2011-03-18 07:44:28 UTC
Another method (probably less efficient wrt processing resources)



SELECT ID, Name FROM someTable a

WHERE Name = 'A' OR NOT EXISTS

(SELECT 1 FROM someTable b

WHERE a.ID = b.ID AND b.Name = 'A')
Ratchetr
2011-03-17 18:01:57 UTC
George beat me too it. My solution was very similar, but with a nested select rather than left join.



SELECT ID,NAME

FROM IDNAMES

WHERE ID NOT IN (select ID from idnames where name = 'A')



UNION



SELECT DISTINCT ID,'A'

FROM IDNAMES

WHERE NAME = 'A'


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...