如何在同一列中获得两行的差异

时间:2013-01-09 11:51:04

标签: mysql sql select row

我必须找到一列表的值的差异作为当前行值 - 一列中某些'n'行的前一行值,并且我没有ID用作参考增量

日期:box_count:total_no_of_boxes_used

1/12/12 2   2
2/12/12 8   6
3/12/12 14  6

我有box_count列,我正在尝试获取total_no_of_boxes_used列。 请帮帮我。

提前致谢

3 个答案:

答案 0 :(得分:2)

鉴于您的记录是按日期排序的.....

查询:

select a.date, a.bc, case when (a.bc-b.bc) is null then a.bc else a.bc-b.bc end tot
from tt a
left join 
tt b
on a.date > b.date
group by b.date
;

结果:

DATE                            BC      TOT
December, 01 2012 00:00:00+0000     2   2
December, 02 2012 00:00:00+0000     8   6
December, 03 2012 00:00:00+0000     14  6
December, 04 2012 00:00:00+0000     23  9

答案 1 :(得分:1)

执行此操作的一种方法是使用相关的子查询,如下所示:

SELECT
  t1.`date`,
  t1.box_count,
  t1.box_count -
  IFNULL((SELECT t2.box_count
          FROM table1 t2
          WHERE t2.`date` < t1.`date`
          ORDER BY t2.`date` DESC
          LIMIT 1), 
        0 ) AS total_no_of_boxes_used
FROM table1 t1;

SQL Fiddle Demo

这会给你:

|                            DATE | BOX_COUNT | TOTAL_NO_OF_BOXES_USED |
------------------------------------------------------------------------
|  January, 12 2012 00:00:00+0000 |         2 |                      2 |
| February, 12 2012 00:00:00+0000 |         8 |                      6 |
|    March, 12 2012 00:00:00+0000 |        14 |                      6 |

答案 2 :(得分:0)

试试这个:

SELECT date, 
       (box_count - @diff) total_no_of_boxes_used, 
       (@diff:=box_count) box_count
FROM table1, (SELECT @diff:=0) A;

选中此SQL FIDDLE DEMO

<强>输出

|                            DATE | TOTAL_NO_OF_BOXES_USED | BOX_COUNT |
------------------------------------------------------------------------
|  January, 12 2012 00:00:00+0000 |                      2 |         2 |
| February, 12 2012 00:00:00+0000 |                      6 |         8 |
|    March, 12 2012 00:00:00+0000 |                      6 |        14 |