简体   繁体   中英

stored procedure to find value in 2 columns out of 3

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

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] - eg 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 eg 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!)

另一种选择:要求在列值中找到零和一。

WHERE 0 IN (prio, prio, prio3) AND 1 IN (prio, prio2, prio3)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM