2

I am trying to write a query which needs to find an ID number from 3 WHERE values based on the result only being equal to 1.

So say i want to find a patient's ID and my where clause matches the firstname, lastname and DOB. If there are 2 results because of duplicates, i need the output to be NIL else it should return the patient ID.

if(select count(*)
from patient
where last_name = 'JAMES' 
and first_name = 'JONES' 
and birth_DtTM = '1980-01-01') > 1
print 'NULL' else return Pat_ID1

This is kind of what i am leading towards.

Thanks guys

Andriy M
  • 76,112
  • 17
  • 94
  • 154

3 Answers3

0
select case when  count(*)> 1
then 'NULL' else Pat_ID1 end 
from patient
where last_name = 'JAMES' 
and first_name = 'JONES' 
and birth_DtTM = '1980-01-01'
group by Pat_ID1
Amir Keshavarz
  • 3,050
  • 1
  • 19
  • 26
0

try below.

;WITH CTE(Pat_ID1,last_name,first_name,birth_DtTM,dup_rows)
as
(
    SELECT Pat_ID1,last_name,first_name,birth_DtTM,ROW_NUMBER() OVER(PARTITION BY last_name,first_name,birth_DtTM ORDER BY Pat_ID1) AS dup_rows FROM patient
)
SELECT 
case when dup_rows>1 then null
            when dup_rows=1 then Pat_ID1
            end
 FROM CTE
RobertKing
  • 1,853
  • 8
  • 30
  • 54
0

You can do it like this:

SELECT
  PatientID = CASE COUNT(*) WHEN 1 THEN MAX(Pat_ID1) END
FROM
  patient
WHERE
  last_name = 'JAMES' 
  AND first_name = 'JONES' 
  AND birth_DtTM = '1980-01-01'
;

The CASE expression will evaluate either to the single Pat_ID1 matching the request or to NULL (if COUNT(*) is anything but 1).

As you can see, the Pat_ID1 value is obtained with the help of an aggregate function (by the way, you can use MIN instead of MAX just as well). This is because the presence of COUNT(*) in the query automatically implies grouping and now, if you want to reference columns of the underlying row set, you must only access their aggregated values.

Andriy M
  • 76,112
  • 17
  • 94
  • 154