Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SSMS 2008 T-SQL JOIN Question

Author  Topic 

funk.phenomena
Posting Yak Master

121 Posts

Posted - 2011-11-08 : 12:39:31
Hi All - I have two tables which I'm running a query on. Here are the simplified versions:

TABLE #1 - CUSTOMER_ORDERS

ORDER_ID CUSTOMER_NAME
1234 JANE SMITH
1235 JIM DOE
1236 JOHN SMITH
1237 KEITH ARTHUR

TABLE #2 - ORDER_DATES

ORDER ID SHIP_DATE
1234 11/01/2011
1234 11/02/2011
1235 11/06/2011
1235 11/07/2011
1236 10/31/2011
1237 09/21/2011
1237 09/22/2011
1237 09/23/2011


The second table has multiple Order IDs since the system generates multiple shipping dates. I'm trying to join the two tables, so that it only outputs unique OrderID based on the earliest Ship_Date. Using the DISTINCT function doesn't fix this, it outputs duplicate ORDER ID rows with different ship dates on each line. Any ideas?

SELECT T1.ORDERID, T2.SHIP_DATE FROM CUSTOMER_ORDERS T1
LEFT JOIN ORDER_DATES T2 ON T1.ORDER_ID = T2.ORDER_ID

I would like the output as follows:


ORDER_ID SHIP_DATE
1234 11/01/2011
1235 11/06/2011
1236 10/31/2011
1237 09/21/2011

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-11-08 : 12:42:10
select *
frmo customer_orders c
left join (select order_id, ship_date = min(ship_date) from order_dates group by order_id) d
on c.order_id = d.order_id


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-08 : 12:45:04
[code]
SELECT ORDERID,SHIP_DATE
FROM
(
SELECT T1.ORDERID, T2.SHIP_DATE,ROW_NUMBER() OVER (PARTITION BY T1.ORDERID ORDER BY T2.SHIP_DATE) AS Rn FROM CUSTOMER_ORDERS T1
LEFT JOIN ORDER_DATES T2 ON T1.ORDER_ID = T2.ORDER_ID
)t
WHERE Rn=1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

funk.phenomena
Posting Yak Master

121 Posts

Posted - 2011-11-08 : 13:12:18
THANK YOU NIGEL !!!!! WORKS AS I HOPED!
Thanks anyways Vivisakh! Nigel beat you to it by a few minutes!!!
Go to Top of Page
   

- Advertisement -