|
假设我有一个包含两列的表格(日期和价格)。如果我选择一个日期范围,那么是否有一种方法可以计算价格随时间变化的次数?
. ?5 I/ P, |4 U8 V5 R( L: z例如:
+ G# X. Y- E e7 O+ E Date | Price
( Z' K7 \* M$ v( H' V5 k! B22-Oct-11 | 3.20( s# o3 C" u7 z2 \. w+ y
23-Oct-11 | 3.40, k/ k6 e P0 w/ C1 v
24-Oct-11 | 3.40+ r/ |5 m$ L) R ]4 l5 U6 k2 w1 S
25-Oct-11 | 3.50
* K4 m# D5 u6 ]8 p3 z* u9 C8 J26-Oct-11 | 3.40
7 u; I% S, H' A4 e- a/ K27-Oct-11 | 3.20
# z- |: ~: q+ u28-Oct-11 | 3.20
3 N# Z: G# }% f3 {9 h! _( W在这种情况下,我希望它返回4个价格变化的计数。* J' j1 V, I5 R8 v' k/ R; c
提前致谢。3 G( J# q; E8 U" z5 Z$ P$ N6 P4 N) k
: {7 ]0 k" q0 m9 F% ~7 q0 u! O, a解决方案:
" @5 ?$ a% _5 v9 b
2 g( @, P3 h7 I0 Q) G: f4 Z7 L$ ^: I/ Q8 ?- S( z
- j- \* l* Q' f- J0 J( B
您可以使用分析功能LEAD并LAG访问结果集的上一行和下一行,然后使用该功能查看是否有更改。7 h7 S t& d, ^8 A. I* T
SQL> ed6 @" U+ m6 i& |, j6 p O+ W
Wrote file afiedt.buf; a: H* j1 g' U* d; S, U: _
1 with t as (" l) U3 {0 g( X/ ]- Q+ o
2 select date '2011-10-22' dt, 3.2 price from dual union all; W* b! p+ o0 H w7 V
3 select date '2011-10-23', 3.4 from dual union all
+ p7 X- X7 l7 e' Z6 Q7 y 4 select date '2011-10-24', 3.4 from dual union all4 p3 B' Y: h- D4 l8 v
5 select date '2011-10-25', 3.5 from dual union all' d- p8 H1 u0 G( C8 q
6 select date '2011-10-26', 3.4 from dual union all! w4 ^* [, q, Q9 d) v
7 select date '2011-10-27', 3.2 from dual union all' \( C4 m; M$ [0 A/ u) z6 Y
8 select date '2011-10-28', 3.2 from dual
1 d5 f# y4 W5 q& j5 K3 S 9 ). x/ D- Q) Z: z" |/ {
10 select sum(is_change)
: f/ }+ P ~$ j 11 from (
I7 W: }! ^( v! S" z+ `3 i 12 select dt,* _7 [# a) S3 n# M" ^' a+ T$ s
13 price,
5 D$ ?/ E! @" O3 O 14 lag(price) over (order by dt) prior_price,
/ W: p. a/ R' q 15 (case when lag(price) over (order by dt) != price; [5 H, ?9 P; n
16 then 1
7 u: A% h c1 I9 T5 T 17 else 0
- a# F7 z' C6 A 18 end) is_change
' Y U0 S+ p0 z7 K; J' T 19* from t)9 z1 x% Q$ ]8 ]" O2 T" c
SQL> /, c6 ~, P, V% B4 d1 O
SUM(IS_CHANGE)
. S9 R) {3 a X# M+ o--------------, A6 E$ O; _6 V# A1 U" D* U# J
4 |
|