使用子查询更新具有排名编号的表

问题描述 投票:0回答:2

我正在使用以下 SQL 查询来更新临时表以便能够确定优先级。

这是我的SQL语句

UPDATE #CARD
SET rank_no = x.no_rank
FROM 
    (SELECT 
         rank_no, chg_tot_amt, 
         ROW_NUMBER() OVER (partition by pt_id ORDER BY [chg_tot_amt]) AS no_rank
     FROM 
         #CARD x 
     WHERE 
         noproc = 2) x
WHERE
    x.no_rank IS NOT NULL

这是我得到的结果:

pt_id   rank_no  chg_tot_amt    no_rank
--------------------------------------
99999990    1      4722.3         1
99999990    1     17712.6         2
99999991    1     13643.26        1
99999991    1     15851.24        2
99999992    1      3814.94        1
99999992    1     18033.78        2
99999993    1     18033.78        1
99999993    1     19915.28        2
99999994    1      3814.94        1
99999994    1     15851.24        2
99999995    1      3814.94        1
99999995    1     15851.24        2
99999996    1     13643.26        1
99999996    1     15851.24        2

此语句将

rank_no
更新为 1,而不是预期的 1,2 或 3。

sql sql-server sql-update sql-server-2016 rank
2个回答
1
投票

您的子查询没有连接条件。

有加入条件:

UPDATE c
SET c.rank_no = x.no_rank
FROM #CARD c
INNER JOIN (
    SELECT
        pt_id, chg_tot_amt, 
        ROW_NUMBER() OVER (PARTITION BY pt_id ORDER BY chg_tot_amt) AS no_rank
    FROM #CARD
    WHERE noproc = 2
   ) x ON c.pt_id = r.pt_id AND c.chg_tot_amt = x.chg_tot_amt
WHERE x.no_rank IS NOT NULL

输出:

pt_id 排名_编号 chg_tot_amt
99999990 1 4722.30
99999990 2 17712.60
99999991 1 13643.26
99999991 2 15851.24
99999992 1 3814.94
99999992 2 18033.78
99999993 1 18033.78
99999993 2 19915.28
99999994 1 3814.94
99999994 2 15851.24
99999995 1 3814.94
99999995 2 15851.24
99999996 1 13643.26
99999996 2 15851.24

小提琴


1
投票

您可以直接更新派生的行编号表,无论如何都不需要联接。

UPDATE x
SET rank_no = x.no_rank
FROM (
    SELECT *,
      ROW_NUMBER() OVER (partition by c.pt_id ORDER BY c.chg_tot_amt) AS no_rank
    FROM #CARD c
    where c.noproc =2
) x;
© www.soinside.com 2019 - 2024. All rights reserved.