MYSQL:根据其他列分组的计数设置列值

时间:2019-10-25 19:20:18

标签: mysql

我有一张桌子,它有以下几列:

npx cypress run

我想根据学校名称的数量在ClassFiveSize和ClassEightSize列中设置值,例如:

+-----------------------------+-------+---------------+----------------+
| School_Name                 | Class | ClassFiveSize | ClassEightSize |
+-----------------------------+-------+---------------+----------------+
| Tando Ghulam Ali-I          |     5 |          NULL |           NULL |
| Tando Ghulam Ali-I          |     5 |          NULL |           NULL |
| Tando Ghulam Ali-I          |     8 |          NULL |           NULL |
| Model School (E.M) Larkano. |     5 |          NULL |           NULL |
| Model School (E.M) Larkano. |     5 |          NULL |           NULL |
| Model School (E.M) Larkano. |     8 |          NULL |           NULL |
| Model School (E.M) Larkano. |     5 |          NULL |           NULL |
| Model School (E.M) Larkano. |     8 |          NULL |           NULL |

请让我知道该怎么做。

我正在做这样的事情:

+-----------------------------+-------+---------------+----------------+
| School_Name                 | Class | ClassFiveSize | ClassEightSize |
+-----------------------------+-------+---------------+----------------+
| Tando Ghulam Ali-I          |     5 |          2    |           1    |
| Tando Ghulam Ali-I          |     5 |          2    |           1    |
| Tando Ghulam Ali-I          |     8 |          2    |           1    |
| Model School (E.M) Larkano. |     5 |          3    |           2    |
| Model School (E.M) Larkano. |     5 |          3    |           2    |
| Model School (E.M) Larkano. |     8 |          3    |           2    |
| Model School (E.M) Larkano. |     5 |          3    |           2    |
| Model School (E.M) Larkano. |     8 |          3    |           2    |

1 个答案:

答案 0 :(得分:1)

您可以在查询中使用条件聚合,该查询将返回每种情况的计数器并将其联接到表中:

update tablename t inner join ( 
  select School_Name, 
    sum(Class = 5) counter5,
    sum(Class = 8) counter8
  from tablename  
  group by School_Name 
) g on g.School_Name = t.School_Name 
set
  t.ClassFiveSize = g.counter5,
  t.ClassEightSize = g.counter8;

请参见demo
结果:

| School_Name                 | Class | ClassFiveSize | ClassEightSize |
| --------------------------- | ----- | ------------- | -------------- |
| Tando Ghulam Ali-I          | 5     | 2             | 1              |
| Tando Ghulam Ali-I          | 5     | 2             | 1              |
| Tando Ghulam Ali-I          | 8     | 2             | 1              |
| Model School (E.M) Larkano. | 5     | 3             | 2              |
| Model School (E.M) Larkano. | 5     | 3             | 2              |
| Model School (E.M) Larkano. | 8     | 3             | 2              |
| Model School (E.M) Larkano. | 5     | 3             | 2              |
| Model School (E.M) Larkano. | 8     | 3             | 2              |