Groups | Blog | Home
all groups > sql server data mining > october 2004 >

sql server data mining : Extracting by oldest date



IT-MAN
10/3/2004 4:35:56 PM
How do I build query to extract the following columns from
two tables?

I need the following as a result:
Order_History.Order_No,
Order_History.Date_Changed,
Employee.Emp_Name
(Join on Emp_ID)

Order_History Table:
Order_No, Date_Changed, Emp_ID
sample data ....
1001, 1/1/2000, aab
1001, 2/1/2000, aab
1001, 2/15/2000, ddd
1001, 3/10/2000, dbc

Employee Table:
Emp_ID, Emp_Name

The problem is this: I want the Distinct order_no with the
oldest date including the Emp_Name, so from the above
tables the following will be the correct result:
1001, 1/1/2000, Jack Smith (aab)

I cannot include the Emp_ID with Select Distinct or use Min
(Date_Changed) to get the oldest date, because any of
these options can only return two columns (as far as I
know) If I use Distinct and include Emp_ID I get the
following (I only want the first row with the oldest date):
1001, 1/1/2000, aab
1001, 2/1/2000, aab


Any help will be appreciated
Thanks
anonymous NO[at]SPAM discussions.microsoft.com
10/3/2004 9:45:25 PM
Adam,
Thank you for the reply
The sub query you suggest cannot be based on the user_id
though.

This is the process flow behind it:
1)We want to generate a list of orders (all orders)
showing date created and employee name - unfortunately the
user info is kept in the Order_History

2)As per the sample, there are multiple rows for each
order, including the last_date_changed and User_id
1001, 1/1/2000, aab
1001, 2/1/2000, aab
1001, 2/15/2000, ddd
1001, 3/10/2000, dbc

The following query will give me the correct result, but
does not include the user information - i need the user
information included:

SELECT Order_No, min(Changed_Date) as MyDate
FROM Order_History
GROUP BY Order_No

So how do I get the above result + user name?

Hope this gives you more info
Thanks
Marius


[quoted text, click to view]
Adam Machanic
10/3/2004 10:20:37 PM
Marius,

I don't quite understand how you need the JOIN done, but you can start with
something like:

SELECT Order_History.Order_No,
Order_History.Date_Changed,
Employee.Emp_Name
FROM Order_History
JOIN Employee ON Order_History.Emp_Id = Employee.Emp_Id
WHERE Order_History.Date_Changed =
(SELECT MIN(Date_Changed)
FROM Order_History OH1
WHERE OH1.Emp_Id = Employee.Emp_Id)


[quoted text, click to view]

Adam Machanic
10/4/2004 9:25:20 AM
Does this work:


SELECT Order_History.Order_No,
Order_History.Date_Changed,
Employee.Emp_Name
FROM Order_History
JOIN Employee ON Order_History.Emp_Id = Employee.Emp_Id
WHERE Order_History.Date_Changed =
(SELECT MIN(Date_Changed)
FROM Order_History OH1
WHERE OH1.Order_No = Order_History.Order_No)


[quoted text, click to view]

anonymous NO[at]SPAM discussions.microsoft.com
10/4/2004 1:05:24 PM
It worked!
You are the man - The champ - The Guru

Thanks
Marius

[quoted text, click to view]
AddThis Social Bookmark Button