MySQL如何在一个查询中使用GROUP BY返回整体COUNT和COUNT

时间:2014-10-19 12:47:10

标签: mysql count group-by

我有以下查询:

SELECT location, COUNT( location ) AS Total, (

SELECT location, COUNT( location ) AS Responses
FROM  `trespondent` 
WHERE completion_status IN ('Started',  'Complete')
GROUP BY location
)

FROM  `trespondent` 
GROUP BY location

这会带来错误:

  

操作数应包含1列

这是完全正确的,因为会有多行。

我想在一个查询中尝试实现的目标是在“位置”中恢复每个选项的总数。然后是已经开始或已经完成的数字'对于'位置'中的每个选项。

如果在单个查询中可以提供任何建议,如果是这样,欢迎使用任何指针。

3 个答案:

答案 0 :(得分:1)

您可以使用UNION子句更改您的查询,以使用这两个版本的查询并获得整体结果

SELECT location, COUNT( location ) AS Total
FROM  `trespondent`
GROUP BY location

UNION ALL

SELECT location, COUNT( location ) AS Responses
FROM  `trespondent` 
WHERE completion_status IN ('Started',  'Complete')
GROUP BY location

或者可能使用JOIN加入查询结果,例如

SELECT t1.location as T1location, 
COUNT( t1.location ) AS Total,
tab.Responses,
tab.location as tablocation
FROM  `trespondent` t1 
JOIN
(
SELECT location, COUNT( location ) AS Responses
FROM  `trespondent` 
WHERE completion_status IN ('Started',  'Complete')
GROUP BY location
) tab
ON t1.location = tab.location
GROUP BY t1.location

答案 1 :(得分:1)

您可以使用条件和进行第二次计算:

SELECT 
  location, 
  COUNT(*) AS Total, 
  SUM( IF(completion_status IN ('Started',  'Complete'), 1, 0)) as 'Responses'
FROM  trespondent 
GROUP BY location

答案 2 :(得分:0)

这个怎么样?

SELECT location, COUNT( location ) AS Total,
       (SELECT COUNT( location ) AS Responses
        FROM  `trespondent` 
        WHERE completion_status IN ('Started',  'Complete')
       )
FROM  `trespondent` 
GROUP BY location;

也就是说,总计的子查询不需要group by

编辑:

如果您想要对两个状态的每个位置进行计数,那么只需使用条件聚合:

SELECT location, COUNT(*) AS Total, SUM(completion_status IN ('Started',  'Complete'))
FROM  `trespondent` 
GROUP BY location;

这似乎是最简单的解决方案。