[英]MYSQL: Setting column value based on count grouped by other columns
I have the table, which has following Columns:我有一张桌子,它有以下几列:
+-----------------------------+-------+---------------+----------------+
| 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 |
I want to set values in ClassFiveSize & ClassEightSize columns based on the count of School names, like:我想根据学校名称的数量在 ClassFiveSize 和 ClassEightSize 列中设置值,例如:
+-----------------------------+-------+---------------+----------------+
| 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 |
Please let me know how to do it.请让我知道该怎么做。
I am doing something like this:我正在做这样的事情:
update tableName t
inner join (
select School_Name, count(*) counter
from tableName
where Class=8 group by School_Name ) g on g.School_Name = t.School_Name
set t.ClassEightSize = case when t.Class=8 then g.counter else 0 end;
You can use conditional aggregation in a query that returns the counters for each case and join it to the table:您可以在查询中使用条件聚合,该查询返回每种情况的计数器并将其连接到表中:
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;
See the demo .请参阅演示。
Results:结果:
| 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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.