车辆里程的SQL查询

时间:2017-04-02 00:14:26

标签: sql

我正在尝试为我的大学课程设计一个车队管理数据库。

目前,我的查询搜索我创建的“视图”,并根据年份计算员工总里程数,从他们的起始里程减去他们的旅程结束里程,这样可以在结果中进行工作和分组。 但是,无论我怎么努力,我不能做的就是询问员工每年从我创造的结果中做出超过25,000英里的行动。我不确定是否可以查询别名列的结果?

SELECT Assigned_Vehicle_id "Assigned Vehicle id", 
       Payroll_Number "Payroll Number", First_Name "First Name",
       Surname, Vehicle_Registration "Vehicle Registration",
       Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
       SUM(End_Miles - Start_Miles) "Total Miles Driven"
  FROM Destinations
 WHERE YEAR(Start_Date) = 2016
 GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
       Vehicle_Registration, Manufacturer_Name, Model_Name;

2 个答案:

答案 0 :(得分:1)

试试这个。请注意GROUP BY

之后的HAVING子句
 SELECT Assigned_Vehicle_id "Assigned Vehicle id", 
 Payroll_Number "Payroll Number", First_Name "First Name", Surname,
 Vehicle_Registration "Vehicle Registration", Manufacturer_Name 
 "Manufacturer Name",
 Model_Name "Model Name", SUM(End_Miles - Start_Miles) "Total Miles Driven" 
 FROM Destinations 
 WHERE YEAR(Start_Date) = 2016 
 GROUP BY 
 Assigned_Vehicle_id, Payroll_Number, First_Name, Surname, 
 Vehicle_Registration, Manufacturer_Name, Model_Name
 HAVING SUM(End_Miles - Start_Miles) > 25000

答案 1 :(得分:0)

在某些方面,Jasonanswer中建议的HAVING子句是好的,简单的,很可能是预期的 - 即使它涉及写出表达式两次而不是允许你使用别名。我相信,有些DBMS允许您在后续子句中使用输出列别名,例如GROUP BY或HAVING子句,但标准没有,因此大多数DBMS都没有。

然而,还有另一种可能有效的选择:

SELECT "Assigned Vehicle id", 
       "Payroll Number", "First Name",
       Surname, "Vehicle Registration",
       "Manufacturer Name", "Model Name",
       "Total Miles Driven"
  FROM (SELECT Assigned_Vehicle_id "Assigned Vehicle id", 
               Payroll_Number "Payroll Number", First_Name "First Name",
               Surname, Vehicle_Registration "Vehicle Registration",
               Manufacturer_Name "Manufacturer Name", Model_Name "Model Name",
               SUM(End_Miles - Start_Miles) "Total Miles Driven"
          FROM Destinations
         WHERE YEAR(Start_Date) = 2016
         GROUP BY Assigned_Vehicle_id, Payroll_Number, First_Name, Surname,
               Vehicle_Registration, Manufacturer_Name, Model_Name
       ) AS Mileages_In_2016
 WHERE "Total Miles Driven" > 25000

这会在FROM子句中将原始查询作为“子查询”运行,这允许您在外部查询中针对外部查询中的"Total Miles Driven"列编写过滤器。