Hi
I have a load of transaction data which I need to join to a rate table to find the correct rate to price on. The join should be one-to-one and the selection of the correct rate is based on various columns in both tables which should either match or, where the rate table contains 'NA', allow any value from the transaction table. Where there is a specific match, this should be selected rather than a join where 'NA' is used to allow any other value in the transaction.
Here is the CREATE script for the transaction table:
CREATE TABLE [dbo].[job_variables]( [job_no] [int] NOT NULL, [product_code1] [nvarchar](2) NULL, [product_code2] [nvarchar](2) NULL, [customer_code] [nvarchar](8) NULL, [area1] [nvarchar](8) NULL, [area2] [nvarchar](8) NULL,
[group_code] [nvarchar](8) NULL)
And for the rate table:
CREATE TABLE [dbo].[ratecriteria]( [product_code1] [nvarchar](255) NULL, [product_code2] [nvarchar](255) NULL, [customer_code] [nvarchar](255) NULL, [area1] [nvarchar](255) NULL, [area2] [nvarchar](255) NULL,
[group_code] [nvarchar](255) NULL,)
The combinations used to join the tables should be attempted in this order, where X = a match and NA = ratecriteria value is 'NA' so allow all from job_variables. As the data tables need to join one-to-one, once a transaction meets the join criteria, it cannot be joined to another ratecriteria record.
Firstly, where ratecriteria.group_code = 'NA' and customer_key matches:
product_code1 | product_code2 | area1 | area2 | customer_code | group_code | |
X | X | X | X | X | NA | |
X | X | X <------> | X | X | NA | (area1 and area2 reciprocated) |
X | X | X | NA | X | NA | |
X | X | NA | X | X | NA | |
X | X | NA | NA | X | NA | |
NA | X | X | X | X | NA | |
NA | X | X | NA | X | NA | |
NA | X | NA | X | X | NA | |
NA | X | NA | NA | X | NA |
Then, where ratecriteria.customer_code = 'NA' and group_code matches:
product_code1 | area1 | area2 | customer_code | group_code | |
X | X | X | NA | X | |
X | X <------> | X | NA | X | (area1 and area2 reciprocated) |
X | X | NA | NA | X | |
X | NA | X | NA | X | |
X | NA | NA | NA | X | |
NA | X | X | NA | X | |
NA | X | NA | NA | X | |
NA | NA | X | NA | X | |
NA | NA | NA | NA | X |
And finally, where both ratecriteria.customer_code and ratecriteria.group_code = 'NA':
product_code1 | area1 | area2 | customer_code | group_code | |
X | X | X | NA | NA | |
X | X <------> | X | NA | NA | (area1 and area2 reciprocated) |
X | X | NA | NA | NA | |
X | NA | X | NA | NA | |
X | NA | NA | NA | NA | |
NA | X | X | NA | NA | |
NA | X | NA | NA | NA | |
NA | NA | X | NA | NA | |
NA | NA | NA | NA | NA |
I am working with SQL Server 2012 in SSMS. Any help greatly appreciated, let me know if I need to provide more info.
Thanks