Reputation: 135
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 e.g
where transactiontype!=void and transactiontype='charges'.
I need to keep the latest 'charges' row. below is the table
Upvotes: 1
Views: 139
Reputation: 8033
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
Upvotes: 2
Reputation: 1173
Use ranking function with partition by patid and order by chargeid DESC then filter out unnecessary records from where clause.
Upvotes: 1