0

id我有一张这样的桌子

|----|-----------|--------|
| 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),如果有意义的话,只需要计算该种族行的adno。

4

2 回答 2

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;
于 2013-01-21T15:25:35.487 回答
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
于 2013-01-21T15:29:48.263 回答