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.
| Author |
Topic |
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2011-07-27 : 14:13:24
|
| Hi All - I have the following tables:Table #1 - OrdersOrderNum : OrderType12346789 - Customer12346790 - Customer12346791 - Business12346792 - GovernmentTable #2 - OrderTypesOrderType - RegionCustomer - NorthWestCustomer - SouthWestCustomer - NorthWestBusiness - SouthEastBusiness - NorthWestBusiness - NorthEastGovernment NorthEastGovernment SouthEastI'm joining the tables based on (obviously) Order Type. Although there are multiple entries in the second table related to my JOIN field, I only want it to join and display ONLY the first available record it can find a match on, so that it displays the following:OrderNum : OrderType : OrderRegion12346789 - Customer : NorthWest12346790 - Customer : NorthWest12346791 - Business : SouthEast12346792 - Government: NorthEastThe syntax below still displays duplicate order numbers with multiple regions. What is wrong with my syntax that's causing this?SELECT DISTINCT T1.OrderNum, T1.OrderType, T2.OrderRegion from ORDERS T1LEFT JOIN OderTypes T2ON T1.ORDERTYPE = T2.ORDERTYPETHANKS! |
|
|
Ghanta
Yak Posting Veteran
96 Posts |
Posted - 2011-07-27 : 16:32:11
|
| Your design is not correct.. you have many to many join... I guess work around would be to create identity column and use MIN() or use CTE. |
 |
|
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2011-07-27 : 16:37:47
|
| The first table has a primary key (OrderNum).It's the second table that has duplicate values on the join column.So really, it's one-to-many. |
 |
|
|
Ghanta
Yak Posting Veteran
96 Posts |
Posted - 2011-07-27 : 17:03:04
|
quote: Originally posted by funk.phenomena The first table has a primary key (OrderNum).It's the second table that has duplicate values on the join column.So really, it's one-to-many.
You are joining using OrderType which is not using PK so where is that one-to-many...Insert into OrdersSelect '12346789', 'Customer'union allSelect '12346790', 'Customer'union allSelect '12346791', 'Business'union allSelect '12346792', 'Government'Insert into OrderTypeSelect 'Customer', 'NorthWest'union allSelect 'Customer', 'SouthWest'union allSelect 'Customer', 'NorthWest'union allSelect 'Business', 'SouthEast'union allSelect 'Business', 'NorthEast'union allSelect 'Government', 'NorthEast'union allSelect 'Government', 'SouthEast'Select a.OrderNum, min(a.OrderType), min(b.Region) from Orders ajoin OrderType bon a.OrderType = b.OrderTypeGroup By a.OrderNumWith CTE as(SELECT ROW_NUMBER() OVER ( ORDER BY CURRENT_TIMESTAMP ) RowNum, OrderType, Regionfrom OrderType)Select a.OrderNum, min(a.OrderType), min(b.Region) from Orders ajoin CTE bon a.OrderType = b.OrderTypeGroup By a.OrderNum |
 |
|
|
|
|
|
|
|