如何根据以下标准编写此SQL

时间:2016-11-05 15:06:01

标签: sql

SELECT TestName,
    SUM(TestFee) AS TestFee ,
    COUNT(*) "No of Tests"
    FROM  ALLPATIENTINFO 
    WHERE ReqDate BETWEEN '2016-11-04' AND '2016-11-05'
    GROUP BY  TestName

此处仅显示与日期相符的Testname,total和count number。但我想显示保存在数据表中的所有testName。如果测试名称超出此日期,那么它只显示testname和testfee&计数不会为零。

2 个答案:

答案 0 :(得分:1)

这里的一个选择是将WHERE子句的逻辑移到SELECT子句中并使用条件聚合:

SELECT TestName,
       SUM(CASE WHEN ReqDate BETWEEN '2016-11-04' AND '2016-11-05'
                THEN TestFee ELSE 0 END) AS TestFee,
       SUM(CASE WHEN ReqDate BETWEEN '2016-11-04' AND '2016-11-05'
                THEN 1 ELSE 0 END) AS "No of Tests in Range",
       COUNT(*) AS "Total No of Test"
FROM ALLPATIENTINFO
GROUP BY TestName

这将保证原始数据集中出现的每个测试名称也会出现在结果集中。

答案 1 :(得分:0)

您可以使用条件聚合:

SELECT TestName,
       SUM(CASE WHEN ReqDate BETWEEN '2016-11-04' AND '2016-11-05' THEN TestFee ELSE 0 END) AS TestFee ,
       SUM(CASE WHEN ReqDate BETWEEN '2016-11-04' AND '2016-11-05' THEN 1 ELSE 0 END) "No of Tests"
FROM  ALLPATIENTINFO 
GROUP BY  TestName;

如果您有一个包含所有测试列表的单独表格,则可以使用LEFT JOIN代替:

SELECT t.TestName, SUM(TestFee) AS TestFee ,
       COUNT(api.testname) "No of Tests"
FROM TESTS t LEFT JOIN
     ALLPATIENTINFO api
     ON t.testname = api.testname AND
        api.ReqDate BETWEEN '2016-11-04' AND '2016-11-05'
GROUP BY t.TestName;

这可能是一个更好的解决方案,因为它将包括所有测试,甚至是那些从未做过的测试。