我有一张桌子
actions
-------
user_id
action
date
如何仅选择每个用户的第一个操作?
示例数据(动作无关紧要,让它为= 0):
预期结果:
答案 0 :(得分:3)
使用窗口函数(标准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
答案 1 :(得分:0)
select a1.*
from actions a1
join
(
select user_id, min(date) as mindate
from actions
group by user_id
) a2 on a1.user_id = a2.user_id and a1.date = a2.mindate