我有一个选择查询,我需要删除或减去两行,并保留最初在where条件中使用的同一patid的最新chargeID 例如
where transactiontype!=void and transactiontype='charges'.
答案 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
样本输入
样本输出
答案 1 :(得分:1)
使用排序功能,按patid进行分区,并按chargeid DESC进行排序,然后从where子句中过滤掉不必要的记录。