2017-01-22 79 views
-1

我試圖回答一個SQL問題的修訂目的,但似乎無法解決如何讓它的工作。有問題的表是:掙扎與SQL子查詢選擇

Tables in question

的問題是要我寫一個SQL命令來顯示誰擁有來自100多個所有行程總距離每一位員工,該員工的姓名和總數員工在所有旅程中使用的升的升數(行程中的升數爲distanceInKm/kmPerLitre)。

到目前爲止,我已經嘗試過的幾個代碼變化開頭:

SELECT 
    name, TravelCost.distanceInKm/Car.kmPerLitre AS "Cost in Litres" 
FROM 
    Employee, Car, TravelCost 
WHERE 
    Employee.id = TravelCost.employeeID 
    AND Car.regNo = TravelCost.carRegNo 

這是在這一點上我有點卡住,任何幫助將不勝感激,謝謝!

+0

我刪除了不兼容的數據庫標記。請標記您真正使用的數據庫。 –

+0

[踢壞的習慣:使用舊式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins。 aspx) - 在ANSI - ** 92 ** SQL標準(** 25年**之前)中將舊式*逗號分隔的表*樣式列表替換爲* proper * ANSI'JOIN'語法不鼓勵使用 –

回答

3

決不使用逗號。 始終使用使用正確,標準,明確的JOIN語法。

你缺少一個GROUP BYHAVING

SELECT e.name, SUM(tc.distanceInKm/c.kmPerLitre) AS "Cost in Litres" 
FROM Employee e JOIN 
    TravelCost tc 
    ON e.id = tc.employeeID JOIN 
    Car c 
    ON c.regNo = tc.carRegNo 
GROUP BY e.name 
HAVING SUM(tc.distanceInKm) > 100; 
+0

謝謝,完美的工作,我曾嘗試過一些非常類似的東西,但錯過了SELECT子句中的SUM。 – Tom

+0

如果我們使用CTE對標準的分組數據進行加入,或者應用更好的perfomant查詢 –

1

使用GROUP BY和HAVING子句的FROM子句中

SELECT NAME, 
     Sum(TravelCost.distanceInKm/ Car.kmPerLitre) AS "Cost in Litres" 
FROM Employee 
     INNER JOIN TravelCost 
       ON Employee.id = TravelCost.employeeID 
     INNER JOIN Car 
       ON Car.regNo = TravelCost.carRegNo 
GROUP BY NAME 
HAVING Sum(distanceInKm) > 100 
1

你需要加入所有的表格,並找到這樣升的總和:

select 
    e.*, 
    sum(distanceInKm/c.kmPerLitre) litres 
from employee e 
inner join travelcost t 
on e.id = t.employeeId 
inner join car c 
on t.carRegNo = c.regNo 
group by e.id, e.name 
having sum(t.distanceInKm) > 100; 

此外,你需要按ID而不是像其他答案所暗示的那樣只是名稱。可以有多個同名的員工。

另外,使用顯式JOIN語法而不是基於舊的逗號的語法。它現代和清晰。

-2
-- **How fool am I! How arrogant am I! I just thought `sum(tc.distanceInKm/c.kmPerLitre)` 
-- may have a problem, since a employee may have multiple cars,and car's kmPerLitre is differenct. 
-- However there is no problem, it's simple and right! 
-- The following is what I wrote, what a bloated statement it is! ** 

-- calcute the total number of litres used by the employee on all journeys 
select e.name, sum(Cost_in_Litres) as "Cost in Litres" 
from (
    select t.employeeID 
     -- calcute the litres used by the employee on all journeys group by carRegNo 
     , sum(t.distanceInKm)/avg(c.kmPerLitre) as Cost_in_Litres 
    from TravelCost t 
    inner join Car c 
     on c.regNo = t.carRegNo 
    where t.employeeID in 
    (-- find the employees who has a total distance from all journeys of more than 100 
    select employeeID 
     from TravelCost 
     group by employeeID 
     having sum(distanceInKm)> 100 
    ) 
    group by t.carRegNo, t.employeeID 
) a 
inner join Employee e 
    on e.id = a.employeeID 
group by e.id,e.name;