在子查询中选择两列

时间:2013-10-10 19:46:55

标签: mysql mysql-error-1241

我有以下SQL语句:

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

我遇到的问题是括号中的SELECT声明 - 我要做的是将整个total人以及已启用的total人带回或完成。

  

1241 - 操作数应包含1列

如果我包含COUNT(Office),则两列不匹配。

如何改进查询以实现我正在寻找的结果集?

Office    Tot   Resp
London    20    2
Leeds     30    17

1 个答案:

答案 0 :(得分:5)

select-list中的任何子查询都必须是标量子查询,即它必须有一列和一行。

但在这种情况下,您根本不需要子查询:

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

诀窍是值为1或0的SUM()与值为1的行的COUNT()相同.MySQL将布尔表达式视为1或0。