簡體   English   中英

無論查詢中的 where 子句如何,如何從表中獲取 max(column_name)?

[英]How to get max(column_name) from a table irrespective of a where clause in the query?

我需要將數據插入表中,其中一列是 seq_number。 我在 select 查詢中有一個 where 子句,我想為要插入的每條記錄插入 max(seq_num)+1。 seq_num 的最大值給了我 where 子句的最大值,而不是表中的實際最大值。

INSERT INTO TABLE_NAME 
SELECT
    NEWID(),
    MAX(SEQ_ORD_R)+1,  -- This should be the max from table irrespective of the where clause
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
FROM TABLE_NAME
WHERE SOFA_K = 'FD5B6BE8-F1CF-42C0-9216-B13163413F96'
SELECT MAX(SEQ_ORD_R) FROM TABLE_NAME INTO @K;
INSERT INTO TABLE_NAME 
SELECT
    NEWID(),
    (SELECT @K := @K+1),
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
FROM TABLE_NAME
WHERE SOFA_K = 'FD5B6BE8-F1CF-42C0-9216-B13163413F96'
INSERT INTO TABLE_NAME 
SELECT
    NEWID(),
    max_seq_r+row_number() over (partition by 1 order by max_seq_r),  -- This should be the max from table irrespective of the where clause
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
FROM TABLE_NAME A inner join 
(select max(SEQ_ORD_R) as max_seq_r from TABLE_NAME) B on 1=1
WHERE SOFA_K = 'xyz'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM