sql - 按计数更新列

时间:2017-02-26 12:15:10

标签: mysql sql sql-server

我在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

它计算表中列出address_oneaddress_two的数量,并将数字存储在相应的address_count中。

但是,这在MySQL中可以正常工作,但在SQL Server中却无效。如何解决此问题?SQL Server

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

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

在任一数据库中,您都可以使用相关子查询。因此,以下代码应该适用于:

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