我有一個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
現在我有888行min_tag = 2和max_tag = 2。這是否意味着每個保單號碼都被複制到我的源表中?
不太熟悉TSQL,但可能它成爲NOT EXISTS子句中的GROUP BY?看起來你沒有使用任何聚合函數來讓GROUP BY做任何事情。 – James
剛剛發表了評論,並再次嘗試 - 但問題依然存在。感謝 – Oleg
['EXCEPT'](https://msdn.microsoft.com/en-us/library/ms188055.aspx)? – HABO