我想选择每个用户 ID 的每个第一个和最后一个事件,如果不存在第一个事件,则只选择最后一个事件。尝试使用 partition over ,但我得到的是前 2 个事件。
输入:
id timestamp event
10096 1545136190 songs
10096 1545136202 tv
10096 1545136239 book
10096 1545136244 eat
10096 1545136252 travel
10096 1545136271 tv
10096 1545136275 laptop
10096 1545313396 sleep
10105 1545464444 book
10105 1545464455 eat
10105 1545464457 travel
10105 1545464460 tv
10105 1545464605 book
10105 1546740388 sleep
10213 1545134176 tv
10213 1545134180 computer
10213 1545134221 play
10213 1545134238 book
10213 1545134267 eat
10213 1545146190 travel
10213 1545146212 play
10213 1545623861 sleep
1053 1545131279 sleep
预期输出:
id timestamp event
10096 1545136190 songs
10096 1545313396 sleep
10105 1545464444 book
10105 1546740388 sleep
10213 1545134176 tv
10213 1545623861 sleep
1053 1545131279 sleep
尝试这样做但没有得到我想要的:
SELECT * FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY id ORDER BY id) as RowNum,
id,
timestamp,
event
FROM
`table`
) MyData
WHERE RowNum < 3