0

这是一张桌子

   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?? 但我正在努力寻找与我需要做的类似的例子。任何人都可以帮助我吗?

4

1 回答 1

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 小提琴示例

于 2013-07-31T03:34:19.473 回答