Jam*_*ama 3 sql oracle date count
说我有一个有两列的表(日期和价格).如果我选择一系列日期,那么有没有办法计算价格变化的数量?
例如:
Date | Price
22-Oct-11 | 3.20
23-Oct-11 | 3.40
24-Oct-11 | 3.40
25-Oct-11 | 3.50
26-Oct-11 | 3.40
27-Oct-11 | 3.20
28-Oct-11 | 3.20
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我希望它返回4个价格变化的计数.
提前致谢.
您可以使用分析函数LEAD并LAG访问结果集的上一行和下一行,然后使用它来查看是否存在更改.
SQL> ed
Wrote file afiedt.buf
1 with t as (
2 select date '2011-10-22' dt, 3.2 price from dual union all
3 select date '2011-10-23', 3.4 from dual union all
4 select date '2011-10-24', 3.4 from dual union all
5 select date '2011-10-25', 3.5 from dual union all
6 select date '2011-10-26', 3.4 from dual union all
7 select date '2011-10-27', 3.2 from dual union all
8 select date '2011-10-28', 3.2 from dual
9 )
10 select sum(is_change)
11 from (
12 select dt,
13 price,
14 lag(price) over (order by dt) prior_price,
15 (case when lag(price) over (order by dt) != price
16 then 1
17 else 0
18 end) is_change
19* from t)
SQL> /
SUM(IS_CHANGE)
--------------
4
Run Code Online (Sandbox Code Playgroud)