2017-01-22 85 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;