我有一张 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/