我有以下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
选择列表中的任何子查询都必须是标量子查询,也就是说它必须有一列和一行。
但在这种情况下,你根本不需要子查询:
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。