我有以下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
答案 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。