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)
 JOIN TABLES TWICE

Author  Topic 

Mondeo
Constraint Violating Yak Guru

287 Posts

Posted - 2007-07-06 : 10:33:44
Table A

VehicleRef, Vehicle
100 AUDI A4
101 BMW 320

Table B

VehicleRef Term Mileage Price
100 2 10000 100.00
100 3 10000 120.00
101 2 10000 130.00
101 3 10000 140.00

I want my results to be

VehicleRef 2YearPrice 3YearPrice
100 100 120
101 130 140

Can I do it in 1 query?

Thanks

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-07-06 : 10:48:28
[code]SELECT VehicleRef,
2YearPrice = MAX(CASE WHEN Term = 2 THEN Price END),
3YearPrice = MAX(CASE WHEN Term = 3 THEN Price END)
FROM TableB
GROUP BY VehicleRef[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

sshelper
Posting Yak Master

216 Posts

Posted - 2007-07-06 : 10:49:46
Try this:

SELECT A.VehicleRef, B.Price AS [2YearPrice], C.Price AS [3YearPrice]
FROM TableA A INNER JOIN TableB B ON A.VehicleRef = B.VehicleRef AND B.Term = 2
INNER JOIN TableB C ON A.VehicleRef = C.VehicleRef AND C.Term = 3

SQL Server Helper
http://www.sql-server-helper.com
Go to Top of Page

Mondeo
Constraint Violating Yak Guru

287 Posts

Posted - 2007-07-06 : 11:03:57
Cheers, works fine.

One small thing though i've created a view using it and the query builder adds this to the beginning on the select statement.

TOP (100) PERCENT

It doesnt affect the results, just curious why it does it.

Thanks
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-07-06 : 23:21:11
Select TOP 100 PERCENT will select all the rows available

Madhivanan

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

- Advertisement -