使用一个id从一列中减去前两行

时间:2013-04-16 20:36:06

标签: sql-server rows subtraction

有谁知道如何只使用一个ID从一列中减去前两行?这是我的示例查询:

SELECT top 2 a.consumption,
             coalesce(a.consumption -
                     (SELECT b.consumption
                      FROM tbl_t_billing b
                      WHERE b.id = a.id + 1), a.consumption) AS diff
FROM tbl_t_billing a
WHERE a.customerId = '5'
ORDER BY a.dateCreated DESC

我想知道如何使用customerId#5使用消费列中的一个id来获得前两行之间的差异。我已经尝试过,但我无法得到正确的查询。有人可以帮帮我吗?谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

;with cte as
(
select consumption, customerId, 
row_number() over (partiton by customerid order by datecreated desc) rn
from tbl_t_billing  where customerId = '5'
)

select a.customerId, a.consumption, 
coalesce((a.consumption - b.consumption), a.consumption) consumption_diff
from cte a left outer join cte b on a.rn + 1 = b.rn
where a.rn = 1

答案 1 :(得分:1)

declare @tbl_t_billing table(consumption int, customerId int, datecreated datetime)
insert into @tbl_t_billing
    values
        (10,5,'20100101'),
        (7,5,'20000101'),
        (9,4,'20100101'),
        (5,4,'20000101'),
        (8,3,'20100101'),
        (3,3,'20000101'),
        (7,2,'20100101'),
        (3,2,'20000101'),
        (4,1,'20100101'),
        (2,1,'20000101')

-- get the difference between the last two consumption values for each customerId
select
    customerId,
    sum(consumption) diff 
from(
    select
        customerId,
        consumption *
            case row_number() over(partition by customerId order by datecreated desc)
                when 1 then 1 when 2 then -1
            end consumption
    from @tbl_t_billing
    ) t
group by customerId