Reputation: 1
I am putting in the samle date and i am supposed to do something similar what i am asking. I want to run a query that would pull values in any two columns out 3 if it has a 1 or if any one column has a 1 it will return just those results. However it should search all three columns and in any of the three columns where it found value as 1 it should return that result. Can anyone please help me with this. Thanks in advance.
ID Patient PatientName prio prio2 prio3
-----------------------------------------------------
1 101563 Robert Riley 1 1 1
2 101583 Cody Ayers 1 0 1
3 101825 Jason Lawler 0 0 1
4 101984 Dustin Lumis 1 0 0
5 102365 Stacy smith 0 0 1
6 102564 Frank Milon 1 1 0
7 102692 Thomas Kroning 1 0 1
8 102856 Andrew Philips 1 0 0
9 102915 Alice Davies 0 0 1
10 103785 Jon Durley 0 0 1
Upvotes: 0
Views: 246
Reputation: 107237
If I understand your question, you want patients which have 1 or 2 of the "Prio*" flags set, but to exclude patients which have zero, or all 3 of the Prio flags set. Assuming that the flags are restricted to a domain of [0,1] - e.g. non nullable bits, then the following should do the trick:
SELECT ID, Patient, PatientName
FROM Patients
WHERE (0 + prio + prio2 + prio3 >= 1) AND (0 + prio + prio2 + prio3 <= 2)
Edit Just a note on performance - you don't mention which SQL, but searching on bit fields like this will almost certainly result in a table scan. To improve performance, you could e.g. on SQL Server create a persisted computed column on prio + prio2 + prio3
and then index this - depending on the distribution of the data, an index would at least have a fighting chance of selectivity.
Edit2 As per Shawnt00's comment, it isn't possible to add bit fields without casting to one of the numeric types. (Thanks!)
Upvotes: 1
Reputation: 17915
Another option: require both a zero and one to be found among the column values.
WHERE 0 IN (prio, prio, prio3) AND 1 IN (prio, prio2, prio3)
Upvotes: 1