简体   繁体   中英

subtract two rows and keep the latest row with the same ID in Sql Server

I have a select query where i need to remove or subtract two rows and keep the latest chargeID for the same patid initially i used in my where condtion eg

 where transactiontype!=void and transactiontype='charges'.

I need to keep the latest 'charges' row. below is the table 表名称tranMaster

Try this 

DECLARE @T TABLE
(
    PatId INT,
    ChargeId INT IDENTITY(1,1),
    TranType VARCHAR(20),
    SomeText VARCHAR(20)
)

INSERT INTO @T
(
    PatId,
    TranType,
    SomeText
)
VALUES(598,'Void','Sample 11'),
    (598,'Charges','Sample 12'),
    (598,'Charges','Sample 13'),
    (611,'Void','Sample 21'),
    (611,'Void','Sample 22'),
    (611,'Charges','Sample 23')

;WITH CTE
AS
(
    SELECT
       RN = ROW_NUMBER() OVER(PARTITION BY PatId,TranType ORDER BY ChargeId DESC),
       *
       FROM @T
)
SELECT
    *
    FROM CTE
       WHERE RN = 1

Sample Input

在此输入图像描述

Sample Output

在此输入图像描述

使用patid分区的排名功能和chargeid DESC的顺序,然后从where子句中过滤掉不必要的记录。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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