简体   繁体   中英

sql - update column by count

I wrote the following query in 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.

However, this works fine in MySQL but not in SQL Server . How can I fix this for 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:

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
                        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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