繁体   English   中英

sql - 按计数更新列

[英]sql - update column by count

我在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修复此问题?

尝试这个:

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

附注 :始终使用显式和现代连接语法,而不是旧的基于逗号的连接。

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

暂无
暂无

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

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