1

我有一张如下表

Value          Count
value1         55
value2         60
value3         65
value4         20
value5         25
value6         45
value7          5
value8         25

我需要一个查询来获取两个连续计数之间的差异并将它们相加。一个条件是,如果下一个值小于前一个值,则考虑下一个值而不是差值。工作如下

Value          Count       Diff         Explanation
value1         55                       No diff as there is no previous value
value2         60            5          (60-55)
value3         75           15          (75-60) 
value4         20           20          (20 as 20 < 75)
value5         25            5          (25-20)
value6         45           20          (45-25)
value7          5            5          (5 as 5 < 45)
value8         25           20          (25-5)

查询应该给出所有差异的总和,即5+15+20+5+20+5+20 = 90

提前感谢您为我制作的精彩查询:-)

4

2 回答 2

2

您可以使用此查询,假设您有一个表tbl(v,c)- v是值字段,c是计数字段。

SELECT t1.v, t1.c as cnt1,
    case 
      when t2.c is null then 0
      when t2.c > t1.c then t1.c
      else t1.c - t2.c
    end as diff
FROM TBL T1
left outer JOIN TBL T2 ON T1.v > T2.v
where not exists (
   SELECT * 
   FROM TBL T3 WHERE T3.V < T1.V AND T3.V > T2.V
)

顺便说一句,您的结果value3应该是 65 而不是 75

我做了一个小提琴来测试它

于 2013-04-19T08:48:59.683 回答
0

你可以coalesce用来解决这个问题

select a.Value,a.count
coalesce(a.count- 
    (select b.countfrom table_name b where b.count= a.count+ 1), a.count) as diff
from table_name  a

但这解决了你的一半问题。我不知道第二个问题的答案

看这里

于 2013-04-19T08:13:35.770 回答