2017-06-02 9 views
0

私は列IDと値を持つテーブルを持っています。同じ値の他のレコードが存在するレコードを低IDで同じ値にしたいとします。私はこれらの数が必要です。私は、この表同じテーブルから同様の列の数を取得する方法

id | value 
---+------ 
1 | 1 
2 | 2 
3 | 1 
4 | 3 
5 | 2 
6 | 1 

を持っている場合たとえば、私がどのようにうまくいかないことができますしかし、私は

select id as id1, value as value1 from table where exists 
(select id as id2, value as value2 from table 
where value2 = value1 and id1 < id2); 

を行うことにより、最初の2つの列を取得することができます答え

id | value | count 
---+-------+------ 
3 | 1 | 1  // 1 other row with value 1 and a lower id 
5 | 2 | 1  // 1 other row with value 2 and a lower id 
6 | 1 | 2  // 2 other rows with value 1 and a lower id. 

が必要カウントを取得する。カウントを取得するにはhavingまたはgroup byを使用する必要がありますか?

答えて

1

あなたはこのためにrow_number()を使用することができます。

select t.* 
from (select t.*, 
      row_number() over (partition by value order by id) - 1 as prev_values 
     from t 
    ) t 
where prev_values > 0; 
関連する問題