0

有谁知道如何仅使用一个 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 行之间的差异。我已经尝试过,但我无法获得正确的查询。有人可以帮我吗?谢谢!

4

2 回答 2

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
于 2013-04-16T21:15:54.583 回答
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
于 2013-04-16T20:42:20.947 回答