如何在sql中编写此SUM查询

时间:2012-11-22 22:30:37

标签: sql database

我有两张桌子

操作员表

proportion, name, routeid

(比例保持%值,例如100 = 100%或50 = 50%,这表示此运营商运营的服务百分比)

路线表

routeid, frequency 

(频率保持每小时的列车数量)

我现在需要做的是写一个查询,它将总结某个运营商每小时的列车数量,其中运营商的名称是Arriva。因此,如果arriva运行100%的某些服务1和50%的服务2,那么它也可以运行。

我认为它看起来像这个psudo代码

All arriva trains per hour = Frequency * (proportion/100)
Where Operators.name = Arriva

3 个答案:

答案 0 :(得分:0)

试试这个

  select SUM((ot.frequency * rt.proportion)/100.0 )
  from operators_table ot 
    join route_table rt on ot.route_id = rt.route_id
  WHERE ot.name = 'Arriva';

答案 1 :(得分:0)

SELECT SUM(frequency * proportion/100) total
FROM Operators JOIN Route USING (routeid)
WHERE Operators.name = 'Arriva'

答案 2 :(得分:0)

declare @operator table 
(
operatorid int not null identity(1,1) primary key clustered
, name nvarchar(64)
, proportion int--(proportion hold % value e.g 100 = 100% or 50 = 50% this shows the % of services ran by this operator)
, routeid int
)


declare @route table
(
    routeid int not null identity(1,1) primary key clustered
    , frequency int --(frequency holds number of trains per hour)
)

--put your insert statements here

select o.operatorid, o.name, sum(r.frequency * (o.proportion/100)) AllTrainsPerHour
from @operator o
left outer join @route r
on o.routeid = r.routeid
where o.name = 'Arriva'
group by o.operatorid, o.name