SQL - 计算有序列表中的更改数

时间:2011-11-08 20:14:20

标签: 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

在这种情况下,我希望它返回4个价格变化的数量。

提前致谢。

3 个答案:

答案 0 :(得分:5)

您可以使用分析函数LEADLAG访问结果集的上一行和下一行,然后使用它来查看是否有更改。

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

答案 1 :(得分:0)

试试这个

select count(*)
from 
(select date,price from table where date between X and Y
 group by date,price )

答案 2 :(得分:0)

取决于Oracle版本,使用分析函数(请参阅Justin Cave的答案)或此

SELECT 
SUM (CASE WHEN PREVPRICE != PRICE THEN 1 ELSE 0 END) CNTCHANGES
FROM
(
SELECT
C.DATE,
C.PRICE,
MAX ( D.PRICE ) PREVPRICE
FROM
(
SELECT 
A.Date, 
A.Price,
(SELECT MAX (B.DATE) FROM MyTable B WHERE B.DATE < A.DATE) PrevDate
FROM MyTable A
WHERE A.DATE BETWEEN YourStartDate AND YourEndDate
) C
INNER JOIN MyTable D ON D.DATE = C.PREVDATE
GROUP BY C.DATE, C.PRICE
)