如何通过mysql查询得到记录差异的总和

时间:2013-04-19 08:07:30

标签: mysql

我有一张表格如下

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

提前感谢您为我准备的精彩查询: - )

2 个答案:

答案 0 :(得分: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

我做了Fiddle来测试它

答案 1 :(得分: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

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

see here