SQL:如何仅获取每个用户的第一个用户操作

标签 sql postgresql greatest-n-per-group

我有一张 table

actions
-------
user_id
action
date

如何只选择每个用户的第一个 Action ?

示例数据(操作无关紧要,让它 = 0):

  • 1 0 2014-05-01
  • 1 0 2014-05-02
  • 1 0 2014-05-03
  • 2 0 2014-05-01
  • 2 0 2014-05-02
  • 3 0 2014-05-08

预期结果:

  • 1 0 2014-05-01
  • 2 0 2014-05-01
  • 3 0 2014-05-08

最佳答案

这可以使用窗口函数(标准 SQL)轻松解决

select user_id, 
       action,
       date
from (
   select user_id,
          action,
          date,
          min(date) over (partition by user_id) as min_date
   from actions
) t
where date = min_date
order by user_id;

使用窗口函数很可能比表上的自连接更快。

使用 Postgres 的 distinct on 运算符很可能比使用窗口函数的解决方案更快(但不能移植到其他 DBMS)。

select distinct on (user_id) user_id, action, date
from actions
order by user_id, date

SQLFiddle:http://sqlfiddle.com/#!15/ae67f/6

关于SQL:如何仅获取每个用户的第一个用户操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702511/

相关文章:

MySQL - 查询日期上方和下方的记录

ruby-on-rails - Rails 3 迁移 : boolean (mysql vs postgreSQL)

mysql 为每个客户选择过去 3 天的行

r - 使用 data.table 按组对对应于最大值的行进行子集化

mysql - 连接两个表,其条件为 "ON"

SQL Server CTE 查询 - 行到单分隔字符串字段

python - 为什么 PostgreSQL 在合并实例时不增加 id_sequence 上的 last_value?

postgresql - Postgresql下使用to_tsquery搜索奇怪的结果

mysql - 从 MySQL 表中选择 10 条具有唯一作者的最新评论

PHP MYSQL 寻找一种对具有多个详细信息和总计的行进行分组的方法