Question

I have the following SQL statement:

SELECT  Office, 
COUNT(Office) As Tot_Part, 
(SELECT Office, COUNT(Office) 
      FROM trespondent 
      WHERE completion_status= 'Started' 
      OR completion_status = 'Complete' 
      GROUP BY Office ORDER BY Office
) As Total_Resp 
FROM trespondent 
WHERE completion_status <> 'New' 
GROUP BY Office 
ORDER BY Office

The issue I am having is the SELECT statement in brackets - what I am trying to do is bring back both the total people overall and then the total people who have Started or Completed.

1241 - Operand should contain 1 column(s)

If I include COUNT(Office), then the two columns don't match.

How can I improve my query to achieve the result set I am looking for?

Office    Tot   Resp
London    20    2
Leeds     30    17
Was it helpful?

Solution

Any subquery in the select-list has to be a scalar subquery, that is it must have one column and one row.

But in this case you don't need a subquery at all:

SELECT 
 Office, 
 COUNT(Office) As Tot_Part, 
 SUM(completion_status IN ('Started', 'Complete')) AS Total_Resp
FROM trespondent 
WHERE completion_status <> 'New' 
GROUP BY Office 
ORDER BY Office

The trick is that SUM() of values that are 1 or 0 is the same as COUNT() of the rows where the value is 1. And MySQL treats boolean expressions as 1 or 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top