2017-06-02 54 views
0

我有一個列id和值的表。我想選擇記錄,其中存在具有相同值但具有較低ID但相同值的其他記錄的記錄。我需要這些的數量。舉例來說,如果我有這樣的表如何從同一個表中獲取類似列的計數

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

我需要的答案

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. 

我可以通過做

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); 

獲得前兩列但是我不知道如何得到點數。我應該使用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; 
相關問題