简体   繁体   English

sql - 按计数更新列

[英]sql - update column by count

I wrote the following query in MySQL : 我在MySQL写了以下查询:

UPDATE mytable atable, 
(SELECT address_one, address_two, COUNT(*) cnt FROM table 
GROUP BY address_one, address_two) btable SET atable.address_count = btable.cnt 
WHERE atable.address_one = btable.address_one AND atable.address_two = btable.address_two

it counts how much address_one AND address_two is listed in the table and stores the number in the respective address_count. 它计算表中列出的address_oneaddress_two的数量,并将数字存储在相应的address_count中。

However, this works fine in MySQL but not in SQL Server . 但是,这在MySQL运行良好,但在SQL Server How can I fix this for SQL Server ? 如何为SQL Server修复此问题?

Try this: 尝试这个:

update a
set a.address_count = b.cnt
from mytable a
join (
    select address_one,
        address_two,
        COUNT(*) cnt
    from mytable
    group by address_one,
        address_two
    ) b on a.address_one = b.address_one
    and a.address_two = b.address_two

Side note : Always use explicit and modern join syntax instead of old comma based join. 附注 :始终使用显式和现代连接语法,而不是旧的基于逗号的连接。

In SQL Server, this is more efficient using window functions: 在SQL Server中,使用窗口函数更有效:

with toupdate as (
      select t.*,
             count(*) over (partition by address_one, address_two) as cnt
      from mytable t
     )
update toupdate
    set address_count = cnt;

In either database, you can use a correlated subquery. 在任一数据库中,您都可以使用相关子查询。 So the following code should work in both: 因此,以下代码应该适用于:

update mytable
    set address_count = (select count(*)
                         from mytable t2
                         where t2.address_one = mytable.address_one and
                               t2.address_two = mytable.address_two
                        );

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

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