Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Trouble with joining based on various combinations of columns

$
0
0

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_code1product_code2area1area2customer_codegroup_code
XXXXXNA
XXX <------>XXNA(area1 and area2 reciprocated)
XXXNAXNA
XXNAXXNA
XXNANAXNA
NAXXXXNA
NAXXNAXNA
NAXNAXXNA
NAXNANAXNA
 

Then, where ratecriteria.customer_code = 'NA' and group_code matches:

product_code1area1area2customer_codegroup_code
XXXNAX
XX <------>XNAX(area1 and area2 reciprocated)
XXNANAX
XNAXNAX
XNANANAX
NAXXNAX
NAXNANAX
NANAXNAX
NANANANAX

 

And finally, where both ratecriteria.customer_code and ratecriteria.group_code = 'NA':

product_code1area1area2customer_codegroup_code
XXXNANA
XX <------>XNANA(area1 and area2 reciprocated)
XXNANANA
XNAXNANA
XNANANANA
NAXXNANA
NAXNANANA
NANAXNANA
NANANANANA

 

I am working with SQL Server 2012 in SSMS. Any help greatly appreciated, let me know if I need to provide more info.

Thanks


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>