I'm querying tables which use a null value as wildcard, this can be overridden if another row contains a non-wildcard value. E.g.:
Table 1: Customers - containing customers and associated products:
create table #cust (
id int not null,
product varchar(3) not null
)
insert into #cust
values (1,'ABC'),(1,'DEF'),(1,'GHI')
============
id | product
------------
1 | ABC
1 | DEF
1 | GHI
============
Table 2: Rebates - contains the rebate customers receive for each product. A null product field specifies a default rebate, to be applied to all products except any which are overtly specified:
create table #rebate (
cust_id int not null,
product varchar(3) NULL,
rebate numeric(5,2) not null
)
insert into #rebate
values (1,null,0.25),(1,'ABC',0.05)
==========================
cust_id | product | rebate
--------------------------
1 | null | 0.25
1 | ABC | 0.05
==========================
So this customer a receives a 25% rebate for all products except 'ABC' for which they receive 5%.
I was trying to code it in a simple way like this:
select *
from #cust c
left join #rebate r
on c.id = r.cust_id
and c.product = isnull(r.product, c.product)
However, the result of this is duplication on the ABC product (matching the r.product is null, and the r.product = c.product parts of the join):
======================================
id product cust_id product rebate
--------------------------------------
1 ABC 1 NULL 0.25 -- duplication
1 DEF 1 NULL 0.25
1 GHI 1 NULL 0.25
1 ABC 1 ABC 0.05 -- duplication. This is the row needed
=======================================
Any suggestions?