2013-12-18 36 views
1

我想這個查詢插入所有不同網店日期到第二個表,如果他們不存在對網絡商店的DataSetSQL INSERT值不存在

下面的查詢似乎忽略AND t1.[DataSet] = 'webshop'參數並且不插入新的webshop值,因爲它們包含相同的日期範圍,即。它們都包含01/02/2013

INSERT INTO [ImportedDateRange] ([DataSet],[DateRange]) 
select DISTINCT 'webshop', cast(T2.[OrderCreatedDate] as DATE) 
from webshop T2 
left join [ImportedDateRange] T1 
on cast(T2.[OrderCreatedDate] as DATE) = t1.[DateRange] 
where t1.[DateRange] is null 
AND t1.[DataSet] = 'webshop' 

期望的結果是,它輸入所述網絡商店的日期範圍,只有當他們不已經存在的網絡商店(如果查詢運行兩次這個防止重複數據)

DataSet DataRange 
business 01/02/2013 
business 02/02/2013 
business 03/02/2013 
webshop 01/02/2013 
webshop 02/02/2013 
webshop 03/02/2013 
+0

使用組的加入By子句,將組數據集 –

+0

使用,其中n ot exists子句並從您的插入表中選擇連接您的表用於插入值在相應的鍵上進行連接) –

回答

3

你應該將t1.[DataSet] = 'webshop'條件從WHERE類

INSERT INTO [ImportedDateRange] ([DataSet],[DateRange]) 
select DISTINCT 'webshop', cast(T2.[OrderCreatedDate] as DATE) 
from webshop T2 
left join [ImportedDateRange] T1 
on cast(T2.[OrderCreatedDate] as DATE) = t1.[DateRange] 
     AND t1.[DataSet] = 'webshop' 
where t1.[DateRange] is null 
+0

謝謝!完善!! – neeko