0

I am stuck on a SQL query, where I need to count the number of different values in a field.

My query is:

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

But The Results I get back look like this, instead of individual values: Image of test counts, by result

1
  • I see, the answer is actually correct, but it's posting the aggregated value for each record it finds. How would I see one row of data for each area? (There are multiple areas, fyi) Commented Nov 18, 2019 at 19:55

1 Answer 1

5

You can create your own fields using case and then sum them.

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
Sign up to request clarification or add additional context in comments.

2 Comments

And this will be orders of magnitude faster than running sub-queries.
Aside: The term of art for this is conditional aggregation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.