我有一些数据 - 按照LineNum分组 - 我需要做的是 - 删除所有相互设置的行,使用负和正的totalOrg值 - 所以在任何情况下,一行有2个正数和一个否定 - 删除正面和负面(totalOrg)行(其中claimDetailID之外的所有其他值相等)并保留剩余的正数...
DROP TABLE #table
CREATE TABLE #table (linenum int, HCPCSOrg varchar(10), reimbOrg money, unitsOrg int, totalorg money, claimdetailID int, comments varchar(500))
INSERT INTO #table
SELECT 1, '84443', 22.93, 1, -82.00 ,1072766, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 1, '84443', 22.93, 1, 82.00, 1072767, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 1, '84443', 22.93, 1, 82.00, 1072768, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 2, '36415', 3.00, 1, -15.00, 1072769, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 2, '36415', 3.00, 1, 15.00, 1072770, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 2, '36415', 3.00, 1, 15.00, 1072771, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 3, '87621', 47.87, 1, 227.00, 1072772, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 3, '85025', 10.61, 1, 40.00, 1072773, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 3, '85025', 10.61, 1, -40.00, 1072774, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 4, 'G0123', 27.64, 1, -74.00, 1072775, 'Status: A - Found in ClinLab'
UNION ALL
SELECT 4, 'G0123', 27.64, 1, 74.00, 1072776, 'Status: A - Found in ClinLab'
UNION ALL
SELECT 4, '85025', 10.61, 1, 40.00, 1072777, 'Status: N - No Other Lab Codes In Claim - Reimb ClinLab'
UNION ALL
SELECT 5, 'G0123', 27.64, 1, 74.00, 1072778, 'Status: A - Found in ClinLab'
SELECT * FROM #table
答案 0 :(得分:2)
试试这个:
delete from [table]
from
(
select p.claimdetailid p
, n.claimdetailid n
from (
select claimdetailid
, linenum
, hcpcsorg
, reimborg
, unitsorg
, 0-totalorg totalorg
, row_number() over (partition by linenum, hcpcsorg, reimborg, unitsorg, totalorg order by claimdetailid) r
from [table]
where totalorg >= 0
) p
inner join (
select claimdetailid
, linenum
, hcpcsorg
, reimborg
, unitsorg
, totalorg
, row_number() over (partition by linenum, hcpcsorg, reimborg, unitsorg, totalorg order by claimdetailid) r
from [table]
where totalorg <= 0
) n
on n.linenum = p.linenum
and n.hcpcsorg = p.hcpcsorg
and n.reimborg = p.reimborg
and n.unitsorg = p.unitsorg
and n.totalorg = p.totalorg
and n.r = p.r
) x
where [table].claimdetailid in (x.p, x.n);
SQL小提琴:http://sqlfiddle.com/#!6/d8910/4
<强>解释强>
p和n子查询列出正值和负值(我在两者中都包含零,因为我猜这些与自己协调)。
row_number() over (partition by ....
确保匹配比例超过1:1时,只删除匹配对(例如,如果我有2个负值和4个正值,其他所有值相等,则删除后2正值将保持不变。
开头的双from
是删除语句(How to Delete using INNER JOIN with SQL Server?)的作弊内部联接,它允许我轻松地将claimdetail与正值和负值进行比较,并且最有效可用选项(例如,与执行exists
语句或必须重复x
子查询相比较,一次返回正数,一次返回负数。
0-totalorg
将负值转换为正值,因此可以将其与内部联接中的对帐(抵消)正值进行比较。