我有下表
PolicyNumber Premium Commission DataSource EffectiveDate
1 -2.25 -0.41 Internal 31/03/2018
1 160.26 29.14 Internal 31/03/2018
1 98.81 17.96 Internal 31/03/2018
2 361.24 65.67 Internal 31/01/2018
2 570.35 103.70 Internal 31/01/2018
2 -17.05 -3.10 Internal 31/01/2018
3 240.60 0.00 External 31/01/2018
3 196.64 0.00 External 31/01/2018
3 240.60 0.00 External 31/01/2018
3 196.64 0.00 External 31/01/2018
3 -240.60 0.00 External 28/02/2018
3 -196.64 0.00 External 28/02/2018
3 -240.60 0.00 External 28/02/2018
3 -196.64 0.00 External 28/02/2018
3 224.04 107.54 External 28/02/2018
3 176.97 84.95 External 28/02/2018
4 504.00 0.00 External 31/01/2018
4 68.33 0.00 External 31/01/2018
4 504.00 0.00 External 31/01/2018
4 68.33 0.00 External 31/01/2018
4 -504.00 0.00 External 28/02/2018
4 -68.33 0.00 External 28/02/2018
4 -504.00 0.00 External 28/02/2018
4 -68.33 0.00 External 28/02/2018
4 453.55 217.70 External 28/02/2018
4 61.44 29.49 External 28/02/2018
我需要排除所有与前一个具有相同绝对值的负溢价值。例如,PolicyNumber 3,Premium 240.60和196.64由负溢价-240.60和-196.64调整。我需要排除PolicyNumber 3.
我希望最终结果如下表所示。
PolicyNumber Premium Commission DataSource EffectiveDate
1 -2.25 -0.41 Internal 31/03/2018
1 160.26 29.14 Internal 31/03/2018
1 98.81 17.96 Internal 31/03/2018
2 361.24 65.67 Internal 31/01/2018
2 570.35 103.70 Internal 31/01/2018
2 -17.05 -3.10 Internal 31/01/2018
我已尝试过以下查询,但它没有给出我的期望
with cte as
( select distinct a.PolicyNumber, a.datasource, a.EffectiveDate from InsuranceTable a
inner join (select PolicyNumber, premium, EffectiveDate, datasource
from InsuranceTable) b on a.PolicyNumber = b.PolicyNumber
where a.premium < 0 and a.EffectiveDate = b.EffectiveDate and a.datasource = b.datasource and b.premium > 0 )
select x.PolicyNumber, x.premium, x.EffectiveDate, x.Commission, x.datasource from InsuranceTable x
inner join cte y on x.PolicyNumber = y.PolicyNumber and x.datasource = y.datasource
order by x.PolicyNumber, x.EffectiveDate
我正在使用Microsoft SQL Server 2012.感谢大家的帮助。
答案 0 :(得分:1)
下面的CTE发现所有具有溢价的保单都被相同金额的负保费抵消。它通过政策和保费的绝对值汇总来实现。然后,我们只需要一个非常简单的查询来获取您想要查看的策略。
WITH cte AS (
SELECT DISTINCT PolicyNumber
FROM InsuranceTable
GROUP BY PolicyNumber, ABS(Premium)
HAVING COUNT(*) > 1 AND MAX(Premium) <> MIN(Premium)
)
SELECT t1.*
FROM InsuranceTable t1
WHERE NOT EXISTS (SELECT 1 FROM cte t2 WHERE t1.PolicyNumber = t2.PolicyNumber);