Question

I have this Query(using SQL Server 2008):

SELECT  
    ISNULL(tt.strType,'Random'), 
    COUNT(DISTINCT t.intTestID) as Qt_Tests,    
    COUNT(CASE WHEN sd.intResult=4 THEN 1 ELSE NULL END) as Positives
FROM TB_Test t 
LEFT JOIN TB_Sample s ON t.intTestID=s.intTestID 
LEFT JOIN TB_Sample_Drug sd ON s.intSampleID=sd.intSampleID
LEFT JOIN TB_Employee e ON t.intEmployeeID=e.intEmployeeID
LEFT JOIN TB_Test_Type tt ON t.intTestTypeID=tt.intTestTypeID
WHERE 
    s.dtmCollection BETWEEN '2013-06-01 00:00' AND '2013-08-31 23:59'
    AND f.intCompanyID = 91
GROUP BY    
    tt.strType

The thing is each sample has four records on sample_drug, which represents the drugs tested on that sample. And the result of the sample can be positive from one to four drugs at the same time. What I need to show in the third column is just if the sample was positive, no matter how many drugs. And I can't find a way to do that, because i need the CASE WHEN to know that i want all the Results = 4 but just from unique intSampleIDs.

Thanks in advance!

Was it helpful?

Solution

If I understand correctly, the easiest way is to use max() instead of count():

SELECT ISNULL(tt.strType,'Random'), 
       COUNT(DISTINCT t.intTestID) as Qt_Tests,    
       max(CASE WHEN sd.intResult = 4 THEN 1 ELSE NULL END) as HasPositives
. . . 

EDIT:

If you want the number of samples with a positive result, then use count(distinct) with a case statement.

SELECT ISNULL(tt.strType,'Random'), 
       COUNT(DISTINCT t.intTestID) as Qt_Tests,    
       count(distinct CASE WHEN sd.intResult = 4 THEN s.intSampleID end) as NumPositiveSamples

OTHER TIPS

instead of this:

COUNT(CASE WHEN sd.intResult=4 THEN 1 ELSE NULL END) as Positives

try this:

SUM(CASE WHEN sd.intResult=4 THEN 1 ELSE 0 END) as Positives

Should work if i undestood correctly that you want show that a row in TB_Sample_Drug marked with intResult = 4 (1) or not (null) in the positives column.

    SELECT  
        ISNULL(tt.strType,'Random'), 
        COUNT(DISTINCT t.intTestID) as Qt_Tests,    
        CASE WHEN sd.Positives > 0 THEN 1 ELSE NULL END as Positives
    FROM TB_Test t 
    LEFT JOIN TB_Sample s ON t.intTestID=s.intTestID 
    LEFT JOIN TB_Employee e ON t.intEmployeeID=e.intEmployeeID
    LEFT JOIN TB_Test_Type tt ON t.intTestTypeID=tt.intTestTypeID
    CROSS APPLY (select count(*) as Positives from TB_Sample_Drug sd where s.intSampleID=sd.intSampleID and sd.intResult=4) sd 
    WHERE 
        s.dtmCollection BETWEEN '2013-06-01 00:00' AND '2013-08-31 23:59'
        AND f.intCompanyID = 91
    GROUP BY    
        tt.strType
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top