SELECT字段值减去前一个字段值

时间:2015-03-25 10:50:53

标签: sql sql-server sql-server-2008 tsql

我有一个选择查询,可以获得CarID,月份,里程和二氧化碳排放量。 现在它给每辆车每个月的里程数如下:

month 1: 5000
month 2: 5200
...

我真正需要的是它取当前值减去前一个值。我在某个时间段之间获得数据,并且在该时间段之前我已经包含了一个里程数点。因此,有可能获得每月的总里程数,我只是不知道如何。我想要的是这个。

pre timeframe:  5000
month 1:        200
month 2:        150
...

我该怎么做?

编辑:代码,我还没有尝试过任何东西,因为我不知道如何开始这样做。

    resultlist as (
SELECT
    CarID
,   '01/01/2000' as beginmonth
,   MAX(kilometerstand) as Kilometers
,   MAX(Co2Emission) as CO2
FROM
    totalmileagelist
GROUP BY CarID

UNION

SELECT
    CarID
,   beginmonth
,   MAX(kilometerstand) as Kilometers
,   MAX(Co2Emission) as CO2
FROM
resultunionlist
GROUP BY CarID, beginmonth
)

select * from resultlist
order by CarID, beginmonth

Edit2:对代码的解释

在结果列表的第一部分中,我获取每辆车的最新里程数。在第二部分,工会结束后,我每个月每辆车最新里程数。

2 个答案:

答案 0 :(得分:0)

试试这样:

SELECT id, yourColumnValue,
       COALESCE(
       (
       SELECT TOP 1 yourColumnValue
       FROM table_name t
       WHERE t.id> tbl.id
       ORDER BY
             rowInt
       ), 0) - yourColumnValue AS diff
FROM  table_name tbl
ORDER BY
      id

或使用rank()

这样的人
select  rank() OVER (ORDER BY id) as 'RowId', mileage into temptable 
from totalmileagelist 

select t1.mileage - t2.mileage from temptable t1, temptable t2 
where t1.RowId = t2.RowId - 1

drop table temptable

答案 1 :(得分:0)

如果您只想减去之前的milage,请使用lag()函数:

select ml.*,
       (kilometerstand - lag(kilometerstand) over (partition by carid order by month)
       ) as diff
from totalmileagelist ml;

lag()在SQL Server 2012+中可用。在早期版本中,您可以使用相关子查询或outer apply

(我错过了版本,因为它在标题中而不在标签上。)在SQL Server 2008中:

select ml.*,
       (ml.mileage - mlprev.mileage) as diff
from totalmileagelist ml outer apply
     (select top 1 ml2.*
      from totalmileagelist ml2
      where ml2.CarId = ml.CarId and
            ml2.month < ml.month
      order by ml2.month desc
     ) mlprev;