mysql从列中减去两行并放入别名

时间:2013-02-23 08:49:49

标签: mysql sql coalesce subtraction

我的表格 meter_readings 包含以下列:iddate_takenkwh

我正在尝试将kwh列中的两行合并在一起,并将结果放入名为consumption的别名中。

我正在使用:

SELECT id, kwh COALESCE(kwh-(SELECT kwh FROM meter_readings WHERE id= id+1), kwh) AS consumption 
FROM meter_readings; 

我在消费别名中获得的内容与原始kwh相同:

 id   date_taken        kwh        consumption 
  1   2013-01-01      4567.89       4567.89 
  2   2013-01-08      4596.71       4596.71  
  3   2013-01-15      4607.89       4607.89

我想要的是:

 id   date_taken        kwh        consumption 
  1   2013-01-01      4567.89          0
  2   2013-01-08      4596.71        28.11
  3   2013-01-15      4607.89        11.18

所以id 1 = 0因为这是第一个date_taken kwh读数所以不需要消耗值。这是试图计算一周的每周kwh消耗量。

2 个答案:

答案 0 :(得分:1)

只需为表名赋予别名,并在相关子查询中的表中使用不同的别名。像这样:

SELECT 
  m1.id, 
  m1.kwh,
  COALESCE(m1.kwh - (SELECT m2.kwh 
                     FROM meter_readings AS m2
                     WHERE m2.id = m1.id + 1),
           m1.kwh) AS consumption 
FROM meter_readings AS m1; 

SQL Fiddle Demo

这会给你:

| ID |     KWH | CONSUMPTION |
------------------------------
|  1 | 4567.89 |     1141.18 |
|  2 | 3426.71 |     1181.37 |
|  3 | 2245.34 |     2245.34 |

更新1

对于更新的样本数据,只需在相关子查询中使用WHERE m2.id = m1.id - 1 COALESCE(..., 0),这样第一个将为0.这样:

SELECT 
  m1.id, 
  date_format(m1.date_taken, '%Y-%m-%d') AS date_taken,
  m1.kwh,
  COALESCE(m1.kwh - (SELECT m2.kwh 
                     FROM meter_readings m2
                     WHERE m2.id = m1.id - 1), 0) AS consumption 
FROM meter_readings m1; 

Updated SQL Fiddle Demo

这会给你:

| ID | DATE_TAKEN |     KWH | CONSUMPTION |
-------------------------------------------
|  1 | 2013-01-01 | 4567.89 |           0 |
|  2 | 2013-01-08 | 4596.71 |       28.82 |
|  3 | 2013-01-15 | 4607.89 |       11.18 |

答案 1 :(得分:0)

COALESCE返回第一个非空值,因此您必须在没有COALESCE的情况下尝试此查询,并查看问题是什么