MySQL Sum,Count还是Join?

时间:2017-02-07 13:11:48

标签: php mysql join

我有以下MySQL查询:

SELECT 
Country, City, 
COUNT(City) As Total, 
SUM(completion_status IN ('Started', 'Complete')) AS Total_Resp
FROM trespondent 
WHERE completion_status <> 'New' 
GROUP BY Country, City 
ORDER BY Counntry, City

这带回了我所期望的,这是一个每个都有计数的城市列表,完全没问题

Country     City     Total     Total_Resp
UK          London   150       23
UK          Leeds    150       83
France      Paris    235       99
France      Lyon     421       222

我要做的是将整个国家的总数带回来,所以英国和法国整体看起来像这样:

Country     City     Total_Country   Total_city   Total_Resp
UK          London   300                150       23
UK          Leeds    300                150       83
France      Paris    656                235       99
France      Lyon     656                421       222

现在,我尝试过简单地添加到SQL语句

COUNT(Country) As Total_Country
SUM(Country) As Total_Country

但两者都带回了与城市相同的数量,我现在认为如果不使用JOIN这是不可能的。有人可以建议吗?

提前致谢。

3 个答案:

答案 0 :(得分:1)

您可以使用相关的子查询:

SELECT t1.Country, t1.City, 
       (SELECT COUNT(t2.Country)
        FROM trespondent AS t2
        WHERE t2.Country = t1.Country) AS Total_Country,
        COUNT(t1.City) As Total_city, 
       SUM(t1.completion_status IN ('Started', 'Complete')) AS Total_Resp
FROM trespondent AS t1
WHERE t1.completion_status <> 'New' 
GROUP BY t1.Country, t1.City 
ORDER BY t1.Country, t1.City

答案 1 :(得分:1)

在大多数数据库中,您只需使用窗口函数。在MySQL中,有几种方法。

SELECT r.Country, r.City, rr.Total_Country, COUNT(r.City) As Total, 
       SUM(r.completion_status IN ('Started', 'Complete')) AS Total_Resp
FROM trespondent r JOIN
     (SELECT r2.Country, COUNT(*) as Total_Country
      FROM trespondent r2
      WHERE r2.completion_status <> 'New' 
      GROUP BY r2.Country
     ) rr
     ON r.Country = rr.Country
WHERE r.completion_status <> 'New' 
GROUP BY r.Country, r.City, rr.Total_Country
ORDER BY r.Country, r.City;

虽然您可以通过其他方式(例如相关子查询)来处理此问题,但我怀疑您可能还希望在国家/地区级别汇总其他值。使用子查询更容易添加它们。例如,您也可以轻松添加该国的响应者数量。

答案 2 :(得分:0)

您可以使用CASE。例如:

SELECT COUNT(*) AS total, SUM(CASE WHEN Country = 'France' THEN 1 ELSE 0 END) AS totalFrance