我有这个查询(使用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
事情是每个样本在sample_drug上有四个记录,代表在该样本上测试的药物。并且样品的结果可以同时为一至四种药物呈阳性。 我需要在第三栏中展示的是,无论药物多少,样本都是阳性的。 我找不到办法做到这一点,因为我需要CASE WHEN知道我想要所有结果= 4但只是来自唯一的intSampleIDs。
提前致谢!
答案 0 :(得分:1)
如果我理解正确,最简单的方法是使用max()
代替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
. . .
编辑:
如果您希望结果为阳性的样本数量,请使用count(distinct)
语句使用case
。
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
答案 1 :(得分:0)
而不是:
COUNT(CASE WHEN sd.intResult=4 THEN 1 ELSE NULL END) as Positives
试试这个:
SUM(CASE WHEN sd.intResult=4 THEN 1 ELSE 0 END) as Positives
答案 2 :(得分:0)
如果我理解你想要显示在阳性列中标记为intResult = 4(1)或不是(null)的TB Sample Drug中的行,那么应该有效。
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