Reputation: 998
I table two table where I want to take only unique records. I have created a short SQL query which is as below:
Declare @tempTable AS TABLE(Country VARCHAR(10),PatientId INT)
INSERT INTO @tempTable VALUES ('India',1)
Declare @tempStatus AS TABLE(PatientId INT, status VARCHAR(2))
INSERT INTO @tempStatus VALUES (1,'NA'),(1,'A'),(1,'D'),(1,'R'),(1,'A')
SELECT t.Country,t.PatientId,Status= (CASE
WHEN ts.status='A' THEN 'A'
WHEN ts.status='NA' OR ts.status='D' THEN 'NA'
ELSE 'R' END)
FROM @tempTable t
LEFT JOIN @tempStatus ts ON t.PatientId=ts.PatientId
It return me data as
Scenario :
On the basis of condition it should just return the output as:
Country PatientId Status
India 1 A
Can someone help on this to ignore the duplicates in case statement.
Upvotes: 1
Views: 978
Reputation: 3657
You are looking for some kind of DISTINCT result with joins based on some conditions. If i got it right after 5 times reading.
DECLARE @tempTable TABLE(Country VARCHAR(10),PatientId INT)
INSERT INTO @tempTable VALUES ('India',1), ('Foo', 2) -- added dummy
-- renamed PatientId to PId for easier writing
DECLARE @tempStatus TABLE(PId INT, status VARCHAR(2))
-- added dummy data
INSERT INTO @tempStatus VALUES (1,'NA'),(1,'A'),(1,'D'),(1,'R'),(1,'A'),(2,'NA'),(2,'D'),(2,'R')
SELECT DISTINCT -- only unique rows
Country,
t.PatientId,
-- only D is replaced in your example with NA, else default status
CASE WHEN ts.status = 'D' THEN 'NA' ELSE ts.status END AS Status
FROM @tempTable t
LEFT JOIN @tempStatus ts ON
( -- first condition
(SELECT DISTINCT status FROM @tempStatus WHERE status = 'A' and PId = PatientId) IS NOT NULL
AND PId = PatientId and status = 'A'
) OR
( -- second condition
(SELECT DISTINCT status FROM @tempStatus WHERE status = 'A' and PId = PatientId) IS NULL
AND PId = PatientId
)
Upvotes: 1
Reputation: 95589
Seems like you need to wrap your CASE
expression in a MAX
:
SELECT t.Country,
t.PatientId,
MAX(CASE WHEN ts.status='A' THEN 1 ELSE 0 END) AS Status --Made this shorter
FROM @tempTable t
LEFT JOIN @tempStatus ts ON t.PatientId=ts.PatientId
GROUP BY t.Country,
t.PatientId;
Upvotes: 1