In a sql server 2012 I would like to join a table to other tables by CustomerNumber.
The table called 'Inventory' that I want to join to other tables has the following characteristics:
1. The CustomerNumber is a foreign key reference to the other tables that need to be joined to.
2. I need to pick the most current cust_date for records where the attributeID is either: 52,53,54, or 55.
3. For each attribute value of 52, 53, 54, or 55, there usally between 0 to 50 rows in the inventory table.
4. The attributes id values are 52, 53, 54, and 55 are related to each other by cust_date.
Thus in the Inventory table, I need to correlate these 4 attributes values to each other by finding maximum (most current). I do know that if I can locate the most current cust_date for one attribute I can relate each attribute to each other.
5. I can not join the inventory table to the other tables by Inventory_ID, this that relationship would not help with the query.
Thus I have the following questions:
1. Can you tell me if I should use the query listed below to find the most current customer date, and/or do you have a query that just can suggest? If so, what would the query be? (**Note I found I had to use distinct on the select since each attribute value occurs more than one time in the table. Also attribute value of 52 is always required so it can be related to the other attribute values.)
SELECT distinct CustomerNumber, cust_date
FROM cust_data
INNER JOIN
(
SELECT CustomerNumber, MAX(cust_date) AS cust_date
FROM cust_data
where attributeID = 53
GROUP BY CustomerNumber
) AS T
ON cust_data.CustomerNumber = T.CustomerNumber
AND cust_data.cust_date = T.cust_date
2. How would you join the inventory table to the other tables using the customer number? There are times when there is no attribute values = 52, 53, 54, or 55? Would you show me somet-sql that would solve this issue for me?