Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Join help please... tough query

Status
Not open for further replies.

peac3

Technical User
Jan 17, 2009
226
AU
Hi guys,

I am struggling with query below and hope you guys can help me with this.
I have 2 tables that I need to join which are Sales table and Customer_code_history table as per below.

Code:
[b]Sales[/b]
Sales_Code	Customer_code
ABC	         X-A01
DEF	         X-B01
GHI	         X-C01

[b]Customer_code_history[/b]
Current_Cust_Code	Prev_cust_Code	start_date	end_date
X-A03	                   X-A02	31/01/2016	31/12/9999
X-A02	                   X-A01	20/01/2016	30/01/2016
X-B01	                   NULL	        3/01/2016	31/12/9999
X-C04	                   X-C03	6/03/2016	31/12/9999
X-C03	                   X-C02	31/01/2016	5/03/2016
X-C02	                   X-C01	20/01/2016	30/01/2016

I am trying to get the new customer code from joining the sales table and customer code history table.
The problem is the customer code from the sales table can exist in prev_cust_code or Current_cust_code in customer code history table

The pseudo code is

if the customer code in sales table exist in current cust code column
then take the current cust code and remove the first 2 characters ("X-")​
else if the customer code in sales table not exist in current cust code column but exist in prev code column
then we need to track the current cust code by finding the latest date which is 31/12/9999​
and remove the first 2 characters ("X-")​
else
null​


The expected result would be as per below

Code:
Sales_Code	Customer_code	New_Customer_Code
ABC	            X-A02	    A03
DEF	            X-B01	    B01
GHI	            X-C01	    C04

If you could help me with teradata query that would be much appreciated.

Thanks,
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top