行之间的差异为新列

时间:2013-07-31 03:28:04

标签: sql-server-2008

这是一个表

   RecordID   PrinterID  Date       ColorCount   BWCount     
     1          1          2/1/2013   2000         8000
     2          2          2/1/2013   3000         4000
     3          1          3/1/2013   4000         10000
     4          2          3/1/2013   5500         7000

这些是每月复印页数。我需要做的是添加一些列,计算每台复印机的每月计数之间的差异,以便为每个复印机每月提供一份总页数。

例如,我正在尝试获取结果集

   RecordID   PrinterID  Date       ColorCount   BWCount     ColC           ColB
   1          1          2/1/2013   2000         8000       2000           8000
   2          2          2/1/2013   3000         4000       3000           4000
   3          1          3/1/2013   4000         10000      4000-2000      10000-8000
   4          2          3/1/2013   5500         7000       5500-3000      7000-4000

我认为这需要LEFT SELF JOIN?但我很难找到类似于我需要做的例子。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

试试这个

;with CTE as (
     select
         *,
         row_number() over (partition by PrinterID order by Date) as Row_Num
     from <your table>
)
select
    C1.RecordID, C1.PrinterID,
    C1.Date, C1.ColorCount, C1.BWCount,
    C1.ColorCount - isnull(C2.ColorCount, 0) as ColC,
    C1.BWCount - isnull(C2.BWCount, 0) as ColB
from CTE as C1
    left outer join CTE as C2 on
        C2.PrinterId = C1.PrinterID and C2.Row_Num = C1.Row_Num - 1

请参阅SQL FIDDLE EXAMPLE