0

THANKS EVERYONE - SOLVED!

I have the following code:

SELECT region, division, SUM(staff_count) AS Total_Staff, 
(SELECT COUNT(region) FROM tresults_xyc WHERE division = 'Central' GROUP BY region) AS Total_Responses
FROM  `trespondent_xyc` 
WHERE division = 'Central'
GROUP BY region

It brings back the following:

region  division    Total_Staff Total_Responses
1       Central     212         8
2       Central     168         8
3       Central     164         8
4       Central     180         8

The information contained in the colomns region, division, and Total_Staff are correct.

However, the Total_Responses colomn is not - that is showing the total number of responses for the Division and not each region.

Can anyone advise?

Thanks in advance,

Homer.

1
  • Your inner query has no any reference to region thus counts values for all. Commented Jul 4, 2011 at 12:00

2 Answers 2

2

You have to do this :

SELECT region, division, SUM(staff_count) AS Total_Staff, 
       (
           SELECT COUNT(*) 
           FROM tresults_xyc t2
           WHERE t2.region = t1.region
       ) AS Total_Responses
FROM  `trespondent_xyc` t1
WHERE division = 'Central'
GROUP BY region
Sign up to request clarification or add additional context in comments.

2 Comments

The second query will produce different results
Indeed, the first query worked perfectly. The second produced spurious results!
0

try

SELECT region, division, SUM(staff_count) AS Total_Staff, (SELECT COUNT(region) FROM tresults_xyc WHERE division = 'Central' and region = xx.region GROUP BY region) AS Total_Responses
FROM  `trespondent_xyc` xx 
WHERE division = 'Central'
GROUP BY region

1 Comment

Works, except it brings back NULLS, the code before (first query) brings me back zeros where there are no responses.

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.