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 |
jezeus
Starting Member
1 Post |
Posted - 2007-08-21 : 17:43:07
|
Given the following tables:RefuelCarID OdometerReading LitersGas1 1245 55.251 1457 16.961 1872 34.231 2193 251 2448 20.41 2508 5.521 2663 14.151 3075 41.821 3387 27.772 112145 362 112972 34.242 113357 30.032 113731 29.922 114130 36.72 114535 36.982 114943 41.413 18091 30.253 18291 16.63 18506 18.273 18791 23.373 19065 22.743 19364 28.403 19569 18.65CARCarID Color Make Model1 Blue Ford Taurus2 Green VW Jetta3 Blue Acura 1.7ELTake it as a given that every time a car is refueled, the tank is filled.To determine gas consumption (l/100km), take the LitersGas, divide it by kilometers traveled, and multiply by 100.For example:If the car takes 45 liters of gas, and had traveled 502 km since the previous time it was refueled, the fuel consumption would be: 45 liters / 502 km * 100 = 8.96 l/100km1. Is it possible to make a single sql statement that would determine the fuel consumption and return the following table:OdometerReading Consumption Color Make1245 n/a Blue Ford1457 7.54 Blue Ford1872 8.19 Blue Ford2193 7.78 Blue Ford2448 7.84 Blue Ford2508 8.33 Blue Ford2663 9.03 Blue Ford3075 9.95 Blue Ford3387 8.65 Blue Ford112145 n/a Green VW112972 4.11 Green VW113357 7.79 Green VW113731 7.75 Green VW114130 9.02 Green VW114535 8.88 Green VW114943 10.04 Green VW18091 n/a Blue Acura18291 8 Blue Acura18506 8.37 Blue Acura18791 8.07 Blue Acura19065 8.02 Blue Acura19364 9.36 Blue Acura19569 8.78 Blue Acura2. If you answered yes to question 1, please give the sql statement.If you answered no, please explain why it isn’t possible, what extra information is needed and give a sample sql statement that should give the answer above.-------------------I got this so farSELECT Refuel.OdometerReading, /* Big mess of code */ AS Consumption, CAR.Color, CAR. MakeFROM Refuel, CARWHERE Refuel.CarID = Car.CarIDI'm doubtful that this is the way to do it, but this is all I can remember... can someone help me or point me in the right direction please?-- |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-08-21 : 18:11:28
|
[code]SELECT q.OdometerReading, q.LitersGas / (q.OdometerReading - q.PreviousOdometerReading) * 100.0 AS Consumption, c.Color, c.MakeFROM ( SELECT r.CarID, r.LitersGas, r.OdometerReading, (SELECT MAX(e.OdometerReading) FROM Refuel AS e WHERE e.CarID = r.CarID AND e.OdometerReading < r.OdometerReading) AS PreviousOdometerReading FROM Refuel AS r ) AS qINNER JOIN Car AS c ON c.CarID = q.CarID[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
|
|
|
|