减去两行并在Sql Server中保留具有相同ID的最新行

时间:2018-07-23 05:11:01

标签: sql sql-server

我有一个选择查询,我需要删除或减去两行,并保留最初在where条件中使用的同一patid的最新chargeID 例如

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

我需要保留最新的“费用”行。 下表为table name tranMaster

2 个答案:

答案 0 :(得分:2)

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

样本输入

enter image description here

样本输出

enter image description here

答案 1 :(得分:1)

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