I have a table rep.Ref
containing Date
, Country
and Total_Amt
. I have another table rep.Customer
containing Date, Country
, Customer
and Amt
. If a combination of Date
and Country
does not exist in rep.Customer
for a Customer
, then I want to insert a row into rep.Customer
and set Amt = NULL
for that row. I need to do this for each Customer
where the combination of Date
and Country
does not exist in rep.Customer
.
I have the below code but it does not return any rows to be inserted unless I apply filters for the specific country
and date
that I know are missing (I've commented these out in the code below). And even if I apply the filters the Customer
is returned as NULL
.
INSERT INTO rep.Customer (Date, Country, Customer, Amt)
SELECT oa.Date, oa.Country, dca.Customer, NULL
FROM rep.Ref oa
--FROM (select * from rep.Ref where Dest_Country = 'Chile' and Date = '2018-12-31') oa
LEFT JOIN (
SELECT DISTINCT Date, Country, Customer
FROM rep.Customer
--where Date = '2018-12-31' and Country = 'Chile' and Customer = 'ABC'
) dca ON oa.Date = dca.Date
AND oa.Country= dca.Country
WHERE dca.Customer IS NULL
1条答案
按热度按时间5lwkijsr1#
I think you need to separately select
DISTINCT Customer
andDISTINCT Date, Country
and then cross join them before conditionally merging the resulting Customer/Date/Country combinations back intorep.Customer
.Try something like:
The above uses
NOT EXISTS(...)
, but aLEFT JOIN ... WHERE ... IS NULL
can be used also.See this db<>fiddle for a sample execution.