MySQL多连接/组查询

时间:2013-01-21 15:22:11

标签: mysql sql join

idI有一个像这样的表

|----|-----------|--------|
| ID | Ethnicity | Gender |
| 1  |    2      |   1    |
| 2  |    3      |   1    |
| 3  |    4      |   2    |
|----|-----------|--------|
etc ....

我正试图找回一系列结果,向我展示男性(1)和女性(2)的种族群体

因此,此示例中的结果行将是:

Ethnicity    Male    Female
    2         1        0
    3         1        0
    4         0        1

到目前为止,我接近我想要的东西:

SELECT ethnicity, 
(SELECT 
        count(id)
    FROM
        table_name
    WHERE
        gender = '2' ) as female,
(SELECT 
        count(id)
    FROM
        table_name
    WHERE
        gender = '1') as male
FROM table_name
GROUP BY ethnicity

这给了我:

Ethnicity    Male    Female
2            2        1
3            2        1
4            2        1

但是,如果有意义,那么count(id)只需要计算该种族行的广告。

2 个答案:

答案 0 :(得分:2)

请改为尝试:

SELECT 
  ethnicity, 
  SUM(CASE WHEN gender = 1 THEN 1 ELSE 0 END) AS female,
  SUM(CASE WHEN gender = 2 THEN 1 ELSE 0 END) AS Male
FROM students
GROUP BY ethnicity;

上述内容几乎适用于任何SQL产品,而不仅仅适用于MySQL。但是,如果您愿意,也可以使用此版本,该版本使用MySQL隐式将布尔值转换为整数(true - > 1false - > 0 ):

SELECT 
  ethnicity, 
  SUM(gender = 1) AS female,
  SUM(gender = 2) AS Male
FROM students
GROUP BY ethnicity;

答案 1 :(得分:0)

SELECT 
  ethnicity, 
  CASE WHEN gender = 1 THEN 1 ELSE 0 END AS Male,
  CASE WHEN gender = 2 THEN 1 ELSE 0 END AS Female
FROM students