用另一个colomn来区分差异组

时间:2016-09-20 17:12:26

标签: sql sql-server sql-server-2008 gaps-and-islands

我有一张不同州的车辆里程表。

Table: VehicleState
VehicleID   Mileage   State          DateTime
   1          3000      TX     2016-09-20 03:00:00
   1          3100      TX     2016-09-20 04:00:00
   1          3200      OK     2016-09-20 05:00:00
   1          3300      OK     2016-09-20 06:00:00
   1          3400      OK     2016-09-20 07:00:00
   1          3500      TX     2016-09-20 08:00:00
   1          3600      TX     2016-09-20 09:00:00
   1          3700      TX     2016-09-20 10:00:00
   1          3800      TX     2016-09-20 11:00:00

我希望在每个州获得该车辆的里程数。例如:

VehicleID  Total_Mileage  State     Date
    1          400         TX      2016-09-20
    1          200         OK      2016-09-20

前两行表示车辆行驶至少100英里。第三个记录是3200,但是在那一点上,我不知道车辆在TX或OK之间有多少里程在凌晨4点到凌晨5点之间,我想忽略3100和3200之间的差异.TX的总里程数将是是100(前两行)+ 300(最后四行),这给了我400。

我目前正在使用带有游标的大型存储过程来计算。我想知道是否有更简单的方法来做到这一点。提前谢谢。

1 个答案:

答案 0 :(得分:0)

在OP评论之后,它看起来像row_number()和内部联接。日期不参与分组。

declare @t table (
    VehicleID  int,
    Mileage int,  
    State char(2),
    dt  DateTime);

insert @t(VehicleID, Mileage, State, Dt)
values
 (1,3000,'TX','2016-09-20 03:00:00')
,(1,3100,'TX','2016-09-20 04:00:00')
,(1,3200,'OK','2016-09-20 05:00:00')
,(1,3300,'OK','2016-09-20 06:00:00')
,(1,3400,'OK','2016-09-20 07:00:00')
,(1,3500,'TX','2016-09-20 08:00:00')
,(1,3600,'TX','2016-09-20 09:00:00')
,(1,3700,'TX','2016-09-20 10:00:00')
,(1,3800,'TX','2016-09-20 11:00:00');

with nmb as(
    select VehicleID, Mileage, State, rn=row_number() over(partition by VehicleID order by dt)
    from @t
) 
select t1.VehicleID, t1.State, sum(t2.Mileage - t1.Mileage)
from nmb t1
join nmb t2 on t1.VehicleID = t2.VehicleID and t1.State = t2.State and t1.rn = t2.rn-1
group by t1.VehicleID, t1.State;