在T-SQL查询中选择多个计数字段

Su Llewellyn 0 tsql

我被困在一个SQL查询中,在这里我需要计算一个字段中不同值的数量。

我的查询是:

SELECT 
     Area
     , (SELECT count(TestResult)  FROM TestRun WHERE TestResult = 'PASS' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [Passed]
     , (SELECT count(TestResult)  FROM TestRun WHERE TestResult = 'FAIL' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [Failed]
     , (SELECT count(TestResult)  FROM TestRun WHERE TestResult = 'NOTRUN' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [NotRun]
FROM TestRun
WHERE dbo.TestRun.CreatedDate > '2019-11-18 01:00:00'
GROUP BY dbo.TestRun.Area, TestRun.TestResult, TestRun.CreatedDate

但是我得到的结果看起来像这样,而不是单个值:

kjmerf.. 5

您可以使用大小写创建自己的字段,然后对其求和。

SELECT Area
, SUM(CASE WHEN TestResult = 'PASS' THEN 1 ELSE 0 END) AS Passed
, SUM(CASE WHEN TestResult = 'FAIL' THEN 1 ELSE 0 END) AS Failed
, SUM(CASE WHEN TestResult = 'NOTRUN' THEN 1 ELSE 0 END) AS NotRun
FROM TestRun
WHERE CreatedDate > '2019-11-18 01:00:00'
GROUP BY Area