|
我有表 meter_readings 的列:id,date_taken,kwh。
. \/ `5 F* @7 m2 P1 r2 s5 s- i我正在尝试将列中的两行相减kwh,然后将结果放入一个名为的别名中consumption。
4 p& ?$ F( }$ T我正在使用:
2 D9 o$ t" v5 g: O, r6 \SELECT id, kwh COALESCE(kwh-(SELECT kwh FROM meter_readings WHERE id= id+1), kwh) AS consumption # e* U- J" f1 J( l1 r1 N
FROM meter_readings;6 `- S; ^& | a# ]+ o
我在消费别名中得到的内容与原始别名一样简单kwh:
- X: Q: M, Q/ }# U; e7 [- Q id date_taken kwh consumption 6 _/ I* Q1 \5 h, m4 E9 L
1 2013-01-01 4567.89 4567.89
9 D$ [8 {) k6 D 2 2013-01-08 4596.71 4596.71
" w# z9 j. c/ T5 _' u0 E f 3 2013-01-15 4607.89 4607.89; z0 z% o1 ~0 R4 L- N
我想要的是:+ H- L* S, h2 f
id date_taken kwh consumption
1 p8 F2 L. x# q7 G' s" j 1 2013-01-01 4567.89 0' V2 f, Y4 ?7 a- i& R. a: T5 J% C
2 2013-01-08 4596.71 28.11
# Y( n1 J+ x" F, p7 w 3 2013-01-15 4607.89 11.18
; e5 H+ N( B: f所以id 1 = 0,因为这是第一个date_taken kwh读数,因此不需要消耗值。这试图计算一年中每周的千瓦时消耗量。! m* V: L- e2 Z% y
) C. F' M# o6 H$ y; |7 _ n* e. d解决方案:
4 |( @6 [& O2 x1 j4 Q& w
* a" p8 E4 t( P7 c4 J! S( Q k! f& n0 d' `
7 ]+ q8 L! m& q- T! T9 G: c& i 只需为表名指定一个别名,然后在相关子查询中为表指定一个不同的别名即可。像这样的东西:* F7 ?0 O# _5 U
SELECT
9 _2 H6 X6 _0 K! Z1 q& C) L9 q m1.id,
+ L- G, D- `8 `; R Z) }% b m1.kwh,3 p- Y% g; x$ E- f6 X4 R' w
COALESCE(m1.kwh - (SELECT m2.kwh 9 p; c' C* d& k9 p3 H1 k; o0 R
FROM meter_readings AS m2
7 C8 P" [. P, `0 L* n! ^! z WHERE m2.id = m1.id + 1), i/ h0 l+ [$ ] v1 x4 h
m1.kwh) AS consumption
e9 |! f% j- R7 b! uFROM meter_readings AS m1;& T3 N" I& x' z) Z* `" l
SQL小提琴演示
; N7 L" ]7 \) |2 i这将为您提供:
, {7 K8 c" M t+ j) O, C| ID | KWH | CONSUMPTION |5 f5 M: D5 W3 B9 e) e7 ^
------------------------------1 G U3 J+ D7 p8 c" D
| 1 | 4567.89 | 1141.18 |
) \2 H: q; u9 T6 a8 r# @4 C* j# t| 2 | 3426.71 | 1181.37 |
) I0 K2 I1 ~* R8 A& X2 ]| 3 | 2245.34 | 2245.34 |
9 v3 l9 h7 \/ U9 ?* C7 _# S: ~" m+ E: l* p, I+ r
更新1
R/ x8 J0 m( ^# b) C对于更新的样本数据,只需WHERE m2.id = m1.id - 1在相关子查询中使用with,COALESCE(...,
2 E. }4 ^ ]0 J d, t5 Q0)这样第一个将为0。如下所示:
' S5 [ d: i1 q$ l% VSELECT 0 O# U8 D# E- e5 L' s
m1.id,
: ?" B8 s+ H' M7 |# B! b date_format(m1.date_taken, '%Y-%m-%d') AS date_taken,
4 L! Q* V( k0 `7 ]5 U/ u1 R m1.kwh,' A/ K7 k1 L+ `. u4 j( v2 o( |
COALESCE(m1.kwh - (SELECT m2.kwh
. ]5 o4 R# F: e, E0 y# I/ E' p FROM meter_readings m26 {- c) h, }0 [) k) Z6 s
WHERE m2.id = m1.id - 1), 0) AS consumption ) c, p) R; L' Z9 o
FROM meter_readings m1;
) L4 t$ j' n$ ]$ u0 ]. e7 C更新了SQL Fiddle演示
, A9 b9 |8 U( O这将为您提供:+ M, k- _' {; y( A7 S5 e- v, T
| ID | DATE_TAKEN | KWH | CONSUMPTION |
5 ?2 x( h& p) u/ H5 g-------------------------------------------
) {( {+ |- V0 y) x& || 1 | 2013-01-01 | 4567.89 | 0 |
- @) ?. [4 ]1 z6 [" M% B' R J3 ~7 t| 2 | 2013-01-08 | 4596.71 | 28.82 |
k+ P3 d( l! F- v| 3 | 2013-01-15 | 4607.89 | 11.18 | |
|