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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Multi Cross Reference

Author  Topic 

priestlm
Starting Member

13 Posts

Posted - 2010-01-29 : 06:46:14
Hi guys - is there any way to get both descriptions from table 2 so i see results:


Order CodeDes1 CodeDes2
12345 Description3 Description5
23456 Description2 Description4

Thanks for your help

Table 1
OrderID Code1, Code2
12345 3 5
23456 2 4

Table 2
Code# CodeDescription
1 Description1
2 Description2
3 Description3
4 Description4
5 Description5

raky
Aged Yak Warrior

767 Posts

Posted - 2010-01-29 : 06:59:36
try this


DECLARE @Table1 TABLE ( OrderID INT , Code1 INT,Code2 INT)

INSERT INTO @Table1
SELECT 12345,3,5 UNION ALL
SELECT 23456,2,4

DECLARE @Table2 TABLE ( Code# INT , CodeDescription VARCHAR(100))

INSERT INTO @Table2
SELECT 1, 'Description1' UNION ALL
SELECT 2, 'Description2' UNION ALL
SELECT 3, 'Description3' UNION ALL
SELECT 4, 'Description4' UNION ALL
SELECT 5, 'Description5'

SELECT orderID AS 'Order',t2.CodeDescription AS 'CodeDes1',t3.CodeDescription AS 'CodeDes2'
FROM @Table1 t1
INNER JOIN @Table2 t2 ON t2.Code# = t1.Code1
INNER JOIN @Table2 t3 ON t3.Code# = t1.Code2
ORDER BY orderID
Go to Top of Page

mymatrix
Starting Member

24 Posts

Posted - 2010-01-29 : 07:03:06
Try this..

Select OrderId 'Order',
'CodeDesc1' = (select CodeDescription from Table2 where Code#=Table1.Code1),
'CodeDesc2' = (select CodeDescription from Table2 where Code#=Table1.Code2)

from Table1



thnks
Gaurav

Even my blood group says be -ve to all the negatives.
Go to Top of Page

priestlm
Starting Member

13 Posts

Posted - 2010-01-29 : 07:22:08
Thats brilliant - thank you guys
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-01-29 : 07:51:09
quote:
Originally posted by mymatrix

Try this..

Select OrderId 'Order',
'CodeDesc1' = (select CodeDescription from Table2 where Code#=Table1.Code1),
'CodeDesc2' = (select CodeDescription from Table2 where Code#=Table1.Code2)

from Table1



thnks
Gaurav

Even my blood group says be -ve to all the negatives.


Use Join
There is a chance this will lead to error if more than one value is returned

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-01-29 : 08:40:00
[code]SELECT *
FROM ( SELECT OrderID,CodeDescription,Number
FROM @Table1
UNPIVOT (Value FOR Number IN (Code1, Code2)) Upv
JOIN @Table2 t2
ON Upv.Value = t2.Code#) dd
PIVOT (MAX(CodeDescription) FOR Number IN(Code1, Code2)) Pvt[/code]
Go to Top of Page
   

- Advertisement -