簡體   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