2013-04-16 4 views
0

누구나 어떻게 하나의 ID를 사용하여 하나의 열에서 상위 두 행을 뺄 수 있습니까? 여기 내 샘플 쿼리입니다 :하나의 ID를 사용하여 하나의 열에서 상위 두 행을 뺍니다.

나는 5 CustomerID를 #을 사용 소비 열에서 하나 개의 ID를 사용하여 상위 2 행의 차이를 가져 오는 방법을 알고 싶어
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 

. 시도했지만 올바른 쿼리를 얻을 수 없습니다. 누군가 제발 나를 도와 줄 수 있니? 감사!

답변

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 
+0

이 근무! 감사! –

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 
+1

고맙습니다. 훌륭한 솔루션 ... – MohammedAshrafali