MySQL在同一列上多次计数并将结果插入另一个表

时间:2014-11-03 18:23:09

标签: php mysql

我有两张表如下:

表1

id | fullname | gender | level
------------------------------
1  | Jerry    | Male   | Year 1
2  | Jen      | Female | Year 1
3  | Tom      | Male   | Year 2
4  | Natasha  | Female | Year 2

表2

level | male | female
----------------------
      |      |
      |      |

我想要做的是插入总数。男性和总数没有。从table1到table2组的女性级别。

预期结果应如下表所示:

level  | male | female
---------------------
Year 1 |  1   |  1
Year 2 |  1   |  1

我尝试过以下代码:

INSERT INTO table2 (level, male, female)
SELECT level,
       SUM(gender = 'Male') male,
       SUM(gender = 'Female') female,
FROM table1
GROUP BY level

上面的代码我从这里提出的一个问题中得到了它,因为它似乎与我的问题相同但是当我运行代码时,它并没有给我任何东西。

表格本身有问题吗?或者它来自代码?

1 个答案:

答案 0 :(得分:1)

这将解决您的问题。

INSERT INTO table2 (level,male,female) 
SELECT level, 
SUM(CASE WHEN `gender` = 'Male' THEN 1 ELSE 0 END) AS male, 
SUM(CASE WHEN `gender` = 'female' THEN 1 ELSE 0 END) AS female 
FROM `table1` GROUP BY level