如何从同一个表中获取类似列的计数

时间:2017-06-02 11:54:50

标签: sql postgresql

我有一个包含列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 个答案:

答案 0 :(得分: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;