SQL在值更改时选择计数器

时间:2017-02-27 15:45:34

标签: sql oracle

每次价值变化时,我都需要制作一个计数器。 我有这张桌子:

  Date      |   Quantity
2017-02-01  |    10000
2017-02-02  |    20000
2017-02-03  |    20000
2017-02-04  |    20000
2017-02-05  |    10000
2017-02-06  |    10000

我想做这样的事情:

  Date      |   Quantity   | Counter
2017-02-01  |    10000     |    1
2017-02-02  |    20000     |    2
2017-02-03  |    20000     |    2
2017-02-04  |    20000     |    2
2017-02-05  |    10000     |    3
2017-02-06  |    10000     |    3

我尝试过使用dense_rank和其他功能,但我不能让它看起来像那样,因为当数量为10000时,它会给出相同的计数器号。

我甚至可以提出什么问题?

谢谢!

2 个答案:

答案 0 :(得分:4)

一种简单的方法是使用position和累积总和:

lag()

这些是ANSI标准功能,可在大多数数据库中使用。

答案 1 :(得分:2)

使用MATCH_RECOGNIZE子句的Oracle 12及以上的简单解决方案

with
     test_data ( dt, quantity ) as (
       select date '2017-02-01', 10000 from dual union all
       select date '2017-02-02', 20000 from dual union all
       select date '2017-02-03', 20000 from dual union all
       select date '2017-02-04', 20000 from dual union all
       select date '2017-02-05', 10000 from dual union all
       select date '2017-02-06', 10000 from dual
     )
-- end of test data, for illustration only; WITH clause is NOT part of the query
-- solution (SQL query) begins BELOW THIS LINE
select dt, quantity, mn as counter
from   test_data
match_recognize (
  order by dt
  measures match_number() as mn
  all rows per match
  pattern ( a b* )
  define b as b.quantity = a.quantity
)
;

DT           QUANTITY    COUNTER
---------- ---------- ----------
2017-02-01      10000          1
2017-02-02      20000          2
2017-02-03      20000          2
2017-02-04      20000          2
2017-02-05      10000          3
2017-02-06      10000          3

6 rows selected.