我正在尝试回答SQL问题以进行修订,但似乎无法解决如何使其工作。有问题的表格是:
问题是要求我编写一个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 :(得分:3)
从不在FROM
子句中使用逗号。 始终使用正确的,标准的,明确的JOIN
语法。
您错过了GROUP BY
和HAVING
:
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;
答案 1 :(得分:1)
使用分组和有条款
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
答案 2 :(得分:1)
您需要加入所有表并找到这样的升数:
providers: [DataService]
此外,您需要按ID分组,而不是像其他答案所示的名称分组。可以有多名员工同名。
此外,使用显式JOIN语法而不是旧的基于逗号的语法。它现代而且更加清晰。
答案 3 :(得分:-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;