第一次和第二次在PostgreSQL中出现行id

时间:2015-10-15 13:26:21

标签: postgresql

假设我们有一个带日期的ID列表。我们想知道ids第一次和第二次出现的时间。大约第一次,我创建了一个

的查询
SELECT year, mon, COUNT(id) AS sum_first_id
FROM (
    SELECT DISTINCT
        ON (id) DATE, id
    FROM TABLE
    GROUP BY 2, 1
    ) AS foo
GROUP BY 2, 1
ORDER BY 1, 2;

我认为这很有效。但是,我怎么能找到ID第二次出现的时候?

1 个答案:

答案 0 :(得分:2)

我们假设您有表格table_x

select * 
from table_x
order by 1, 2

 id |    date    
----+------------
  1 | 2015-06-04
  1 | 2015-06-05
  1 | 2015-06-14
  2 | 2015-06-05
  2 | 2015-06-08
  2 | 2015-06-10
  2 | 2015-06-17
  2 | 2015-06-22
(8 rows)

要选择组中的第一个元素,请使用row_number()函数:

select id, date
from (
    select id, date, row_number() over (partition by id order by date) rn
    from table_x
    order by 1, 2
    ) sub
where rn <= 2

 id |    date    
----+------------
  1 | 2015-06-04
  1 | 2015-06-05
  2 | 2015-06-05
  2 | 2015-06-08
(4 rows)

您的查询似乎不正确。

SELECT year, mon, COUNT(id) AS sum_first_id -- what is year, mon?
FROM (
    SELECT DISTINCT
        ON (id) DATE, id
    FROM TABLE
    GROUP BY 2, 1                           -- should be order by 2, 1
    ) AS foo
GROUP BY 2, 1
ORDER BY 1, 2;