2017-02-27 10 views
2

時間内に値が変化するたびにカウンタを作成する必要があります。 私はこのテーブルを持っている:SQL値が変更されたときにカウンタを選択

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の場合は同じカウンター番号を入力してください。

私は何を求めていますか?

ありがとうございました!

+1

を使用しているDBMSの? – jarlh

+0

私はOracleを使用しています –

+0

どのOracleのバージョンですか? Oracle 12以降では、非常に簡単で効率的なMATCH_RECOGNIZEのソリューションがあります。 – mathguy

答えて

4

簡単な方法は、lag()と累積和を使用することです:

select t.date, t.quantity, 
     sum(case when quantity = prev_quantity then 0 else 1 end) over (order by date) as counter 
from (select t.*, lag(quantity) over (order by date) as prev_quantity 
     from t 
    ) t; 

これらはほとんどのデータベースでANSI標準機能と利用可能です。

+0

これは完全に機能しました。ありがとうございました!! –

2

Oracleの12のためにのみ上記のシンプルなソリューション、MATCH_RECOGNIZE句使用して:あなたは

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. 
関連する問題