我有一个CTE,它给了我760行的结果。而且我有另一个SELECT
语句,它给了我722行。
我想看看CTE中存在哪些SELECT
语句中不存在的记录。
我正在使用NOT EXISTS
语句,但由于某种原因它不会给我任何结果。我也试过NOT IN
- 但是相同......没有记录。
;WITH Cte_Policies AS
(
SELECT
PolicyNumber,
ControlNo,
EffectiveDate,
ExpirationDate,
ProducerName,
SUM(BOUND_Premium) as NetWrittenPremium
FROM CatalyticWindEQ
WHERE EffectiveDate >= '05-01-2016' AND EffectiveDate <= EOMONTH(GETDATE())
AND LineName = 'Earthquake' AND Underwriter <> 'Batcheller, Jerry' AND PolicyNumber IS NOT NULL
GROUP BY
ProducerName,
EffectiveDate
,ExpirationDate ,PolicyNumber, ControlNo
)
SELECT PolicyNumber,
ControlNo,
YEAR(EffectiveDate) as PolicyEffectiveYear,
MONTH(EffectiveDate) as PolicyEffectiveMonth,
NetWrittenPremium,
ProducerName as Producer
FROM
Cte_Policies
where
NOT EXISTS
(
SELECT
PolicyNumber
FROM CatalyticWindEQ eq
WHERE EffectiveDate>='05-01-2016' AND EffectiveDate <= EOMONTH(GETDATE()) AND LineName = 'Earthquake' AND Underwriter <> 'Batcheller, Jerry'
AND PolicyNumber IS NOT NULL
and eq.PolicyNumber=Cte_Policies.PolicyNumber
GROUP BY PolicyNumber
)
我已经完成了这个“
; with CTE as
(
SELECT
PolicyNumber,
ControlNo,
EffectiveDate,
ExpirationDate,
ProducerName,
SUM(BOUND_Premium) as NetWrittenPremium
FROM CatalyticWindEQ
WHERE EffectiveDate >= '05-01-2016' AND EffectiveDate <= EOMONTH(GETDATE())
AND LineName = 'Earthquake' AND Underwriter <> 'Batcheller, Jerry' AND PolicyNumber IS NOT NULL
GROUP BY
ProducerName,
EffectiveDate
,ExpirationDate ,PolicyNumber, ControlNo
)
SELECT PolicyNumber,
min(tag) as min_tag,
max(tag) as max_tag
FROM
(
SELECT PolicyNumber, 1 as tag FROM CTE
UNION ALL
SELECT PolicyNumber, 2 as tag FROM CatalyticWindEQ
) U
GROUP BY PolicyNumber
HAVING COUNT(*)=1
答案 0 :(得分:0)
基本策略是选择两个数据集(PolicyNumber
列表),使用union all
收集它们,并找到组合中的唯一项目。
; with CTE as ( ... ) -- the CTE from above
Select PolicyNumber, min(tag) as min_tag, max(tag) as max_tag from (
select PolicyNumber, 1 as tag from CTE
union all
select PolicyNumber, 2 as tag from CatalyticWindEQ -- the source you're matching
) U
Group by PolicyNumber
Having count(*) =1 -- equivalently, having min(tag) = max(tag)
max(tag) = 1
行仅在CTE中。
答案 1 :(得分:0)
你可以使用完整的外部联接来标记差异,在将第二个查询放入另一个cte之后,比如说cte2,你可以尝试这样的事情:
select
a.PolicyNumber,
a.ControlNo,
a.YEAR(EffectiveDate) as PolicyEffectiveYear,
a.MONTH(EffectiveDate) as PolicyEffectiveMonth,
a.NetWrittenPremium,
a.ProducerName as Producer,
b.PolicyNumber
from Cte_Policies as a
full outer join cte2 as b ON b.PolicyNumber=a.PolicyNumber
where
a.PolicyNumber is null -- will show records NOT in cte.
OR b.PolicyNumber is null -- Will show records NOT in cte2.