SQL 2014查询出租车行程数据

时间:2017-02-08 18:00:16

标签: sql-server sql-server-2014

我正在尝试使用Microsoft SQL 2014对以下数据运行查询。 我想找到每小时乘客数量,按天计算行程距离,按小时和天计算的票价金额和总金额。

taxi trip data

PS:我是SQL的新手,我正在做一个类项目。

1 个答案:

答案 0 :(得分:0)

这是一个带有一些日期函数的基本聚合。

declare @table table
    (VendorID int, 
    pickup_datetime datetime, 
    passengercount int, 
    trip_distance decimal (4,2),
    fare_amount decimal (4,2),
    tip_amount decimal (4,2),
    tolls_amount decimal (4,2))

insert into @table
values
(1,'1/8/2015 22:22',3,1.55,5.65,1,1.22),
(1,'1/8/2015 22:45',1,2.35,2.65,2,0.22),

(1,'1/8/2015 23:03',1,4.55,9.55,2,4.22),

(2,'1/9/2015 03:03',3,1.54,0.65,2,1.22),
(2,'1/9/2015 03:16',2,2.05,1.15,3,11.12),

(2,'1/9/2015 04:22',1,3.50,4.25,2,1.83),
(2,'1/10/2015 06:44',4,4.44,3.63,1,1.99)

select
    VendorID, 
    cast(pickup_datetime as date) as DT,
    datepart(hour,pickup_datetime) as HR,
    sum(passengercount) as TotalPassengers,
    sum(fare_amount) + sum(tip_amount) + sum(tolls_amount) as TotalAmount
from 
    @table
group by
    VendorID,
    cast(pickup_datetime as date),
    datepart(hh,pickup_datetime)