如何在postgresql中获取不同组的第一个条目

how to get the first entry from a distinct group by in postgresql

我想找出使用​​他的 anonymous_id 和时间戳注册我的产品(带有 ID)的用户的第一个条目。

因为我知道已经注册并再次访问该页面的用户可以有多个 anonymous_id(f.e 使用多个设备,有新的 cookie 等...),我区分 user_id

我写了一个看起来像这样的代码

SELECT distinct user_id , min(timestamp),anonymous_id
FROM data
group by 1,3

但现在他每次提到用户时都会给我 anonymous_id

user_id | timestamp                   | anonymous_id
 ------ | ----------------------------|-------------
 12     |  2016-07-28 16:19:57.101+00 | x-1
 ------ | ----------------------------|-------------
 12     | 2016-08-24 09:17:21.294+00    y-23 
 12     | 2016-07-27 12:03:25.572+00    y-2345 

我只想看到第一次提到 user_id 12 - 在本例中是时间戳为 2016-07-27 12:03:25.572+00

我如何编写代码才能让我第一次提到 user_id?

您可以使用row_number()window函数:

SELECT user_id, timestamp, anonymous_id
FROM   (SELECT user_id, timestamp, anonymous_id,
               ROW_NUMBER() OVER (PARTITION BY user_id
                                  ORDER BY timestamp ASC) AS rn
        FROM   data) t
WHERE  rn = 1

Postgres 中最快的方法是使用其专有的 distinct on ()

SELECT distinct on (user_id) user_id , timestamp, anonymous_id
FROM data
order by user_id, timestamp;