简体   繁体   English

使用同一表格中另一列的值按组插入列

[英]Insert into a column using group by value of another column of the same table

id name count
------------
1  abc
2  xyz
3  xyz
4  xyz

The following query "select count(name) from temp group by name;" 以下查询“按名称从临时组中选择count(name);” gives me: 给我:

count(name)
--------
1
3

I want this result to be updated to the column 'count'. 我希望将此结果更新为“计数”列。 To be precise I want my table to look like : 确切地说,我希望我的桌子看起来像:

id name count
------------
1  abc   1
2  xyz   3
3  xyz   3
4  xyz   3

You can get those values with a COUNT / GROUP BY. 您可以使用COUNT / GROUP BY获取这些值。 You can do an UPDATE statement which joins your table with the sub query:- 您可以执行UPDATE语句,该语句将表与子查询连接:

UPDATE temp a
INNER JOIN
(
  SELECT name, COUNT(*) AS name_count
  FROM temp
  GROUP BY name
  ) b
  ON a.name = b.name
SET a.name_count = b.name_count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM