0

我有两个相关的表,data(no, name, citycode, age) 和 city(code, city)

表城

  +------+------------+
  | code | city       |
  +------+------------+
  | A1   | Jakarta    |
  | A2   | Bali       |
  | A3   | Semarang   |
  | A4   | Surabaya   |
  | C1   | Dili       |
  | C2   | Jayapura   |
  | C3   | Yogyakarta |
  | C4   | Bandung    |
  +------+------------+

表数据

+----+--------+----------+------+
| no | name   | citycode | age  |
+----+--------+----------+------+
|  1 | Ony    | A3       |   27 |
|  2 | Abri   | A3       |   28 |
|  3 | Denny  | C4       |   27 |
|  4 | Febri  | C1       |   27 |
|  5 | Galih  | C3       |   28 |
|  6 | Yulia  | A2       |   26 |
|  7 | Zening | A1       |   25 |
+----+--------+----------+------+

我想按城市统计 27 岁的员工人数

我的查询:

 select city.city , count(data.name) as Nmb_of_employees
 from city
 left join
 data on data.citycode = city.code
 where data.age = 27
 group by city.city;

结果

+----------+------------------+
| city     | Nmb_of_employees |
+----------+------------------+
| Bandung  |                1 |
| Dili     |                1 |
| Semarang |                1 |
+----------+------------------+

但我想要的结果是这样的

+------------+------------------+
| city       | Nmb_of_employees |
+------------+------------------+
| Jakarta    |               0  |
| Bali       |               0  |
| Semarang   |               1  |
| Surabaya   |               0  |
| Dili       |               1  |
| Jayapura   |               0  |
| Yogyakarta |               0  |
| Bandung    |               1  |
+------------+------------------+

对于上述结果,我应该使用什么查询?

4

3 回答 3

2

您需要删除WHERE导致过滤掉27只有员工年龄的记录的子句。SUM(age = 27)只是一个mysql特定的语句,它基本上总结了表达式的布尔结果。它可以进一步修改为使用CASE对 RDBMS 更友好的SUM(CASE WHEN age = 27 THEN 1 ELSE 0 END).

SELECT  a.City, IFNULL(SUM(age = 27), 0) Nmb_of_employees 
FROM    city a
        LEFT JOIN Data b
            ON a.code = b.cityCode
GROUP   BY a.City
于 2013-09-12T07:58:26.950 回答
1

我认为您希望在ON子句中进行“年龄”检查:

SELECT city.city , count(data.name) AS Nmb_of_employees
  FROM city
       LEFT JOIN data 
              ON data.citycode = city.code 
             AND data.age = 27
 GROUP BY city.city;

否则,您会正确获得表格(带有空格),然后用您的WHERE子句过滤掉空格。

于 2013-09-12T08:02:28.480 回答
0

SELECT DISTINCT city,count(name) FROM city m_t3 LEFT JOIN data m_t4 ON age =27 AND m_t3.code = m_t4.citycode GROUP BY city

于 2013-09-12T10:24:19.787 回答