两列的总和以及单独的select语句

时间:2017-04-11 08:33:47

标签: sql sqlite

我正在处理SQL task,我无法弄清楚如何在显示来自另一个表的信息时从同一个表中获取sum of two columns

我尝试了很多事情,并且花了大约两个小时试图解决这个问题。

我有两张桌子:Employees and Fuel。我显示了所有员工的信息。我必须做出第一条SQL语句:

SELECT firstname, lastname, title, registrationyear, make, model FROM Employees ORDER BY make;

我的Employees table包含以下列:firstname, lastname, employeeid, make, model, registrationyear, title

我的Fuel table包含以下列:currentprice, fueltype, fuelcost, mileage, mileagecount, fuelamount, employeeid, date

我的说明陈述:“一个列表,显示员工当前使用的汽车(我做的第一个SQL语句,所以这个是完成的!) 与上述报告一样,但也包括员工驾驶的总公里数和总燃料成本。“(这是我试图发表声明的任务)

我尝试过使用LIKE, UNION, UNION ALL等等,而我能够做的最好的事情就是列出员工信息和信息的总数,而不是列在另外两个独立的列中。查询中的数据。

我真的被困在这里了。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

你可以使用Inner join& Group By子句如下所述。如果你的意思是别的,请告诉我。

SELECT A.firstname, A.lastname, A.title, A.registrationyear, A.make, A.model,
SUM(B.Column_Having_Kilometer_Driven_Value)
FROM
Employee A
INNER JOIN Fuel B ON A.EmployeeID = B.EmployeeID
Group By A.EmployeeID, A.firstname, A.lastname, A.title, A.registrationyear, A.make, A.model

答案 1 :(得分:0)

这第二项任务比第一项更复杂。

首先,在一行中组合两个或多个表中的列是join的用途,因此您必须根据employeeid加入这两个表。这将返回一个像这样的表

employeeid | other emp fields | fuel date  | other fueld fields
1          | ...              | 01/01/2017 | ...
1          | ...              | 01/02/2017 | ...
2          | ...              | 01/01/2017 | ...
2          | ...              | 02/01/2017 | ...
2          | ...              | 04/03/2017 | ...

从这里开始,您希望每个employee的数据与fuel中与employee相关的行的总和以及group by的内容相加是为了。

使用group by时,您定义了一组定义分组标准的列; yout select语句中的其他所有内容都必须以某种方式进行分组(在您的情况下使用sum),以便group by中的列保持唯一。

您的最终查询将如下所示

select  t1.firstname, t1.lastname, t1.title, t1.registrationyear, t1.make, t1.model,
        sum(t2.mileage) as total_milege,
        sum(t2.fuelcost * t2.fuelamount) as total_fuel_cost
from    Employees t1
join    Fuel t2
on      t1.employeeid = t2.employeeid
group by t1.firstname, t1.lastname, t1.title, t1.registrationyear, t1.make, t1.model

注意:我不知道mileagemileagecount之间的区别,因此涉及这些字段的查询部分可能需要进行一些调整。