【问题标题】:How would I select the max for each row of data based on timestamp and unique id using SQL? [duplicate]如何使用 SQL 根据时间戳和唯一 ID 为每行数据选择最大值? [复制]
【发布时间】:2017-04-28 00:11:05
【问题描述】:

我的数据库中有一个表,我正在使用 SQL 查询从中检索数据。在我的查询中,我正在替换一些文本并使用整数。查询返回以下数据:

user_id | event_code | total_bookmarks | total_folders | folder_depth | ts
0         8            34                6               1              128926
0         8            35                6               1              129001
4         8            18                2               1              123870
6         8            30                2               1              130099
6         8            30                2               1              132000
6         8            30                2               1              147778

我使用的查询是:

SELECT
user_id,
event_code,
CAST(REPLACE(data1, 'total bookmarks', '') AS INTEGER) as total_bookmarks,
CAST(REPLACE(data2, 'folders', '') AS INTEGER) as total_folders,
CAST(REPLACE(data3, 'folder depth ', '') AS INTEGER) as folder_depth,
timestamp AS ts
FROM events
WHERE event_code = 8

我需要在查询中添加什么才能仅选择每个唯一 user_id 的行,每个 id 具有最大 ts(时间戳)?我尝试了 MAX(timestamp),但如果 total_bookmark 不同,我会为相同的 ID 返回两行(例如:user_id 0 一行有 34,另一行有 35)我希望表格如下所示:

user_id | event_code | total_bookmarks | total_folders | folder_depth | ts
0         8            34                6               1              129001
4         8            18                2               1              123870
6         8            30                2               1              147778

【问题讨论】:

  • 为什么用mysqlpostgresql标记?
  • 因为我使用的是 postgresql,但我认为这可以用 mysql 以相同或类似的方式完成
  • 请不要那样做。你在浪费自己和其他人的时间。
  • 投票关闭问题作为重复,因为它是非常常见的greatest-n-per-group 问题的另一个实例。链接到一个对 PostgreSQL 有很好的答案的问题。

标签: sql postgresql max greatest-n-per-group


【解决方案1】:
Declare @table table (user_id int, event_code int, total_bookmarks int, total_folders int, folder_depth int, ts decimal(18,0))
Insert into @table (user_id , event_code , total_bookmarks , total_folders , folder_depth , ts)
Values (0,8,34,6,1,128926),
        (0,8,34,6,1,129001),
        (4,  8,  18 ,  2,   1,   123870),
        (6,  8,  30,   2,   1,   130099),
        (6,  8,  30,   2,   1,   132000),
        (6,  8,  30,   2,   1,   147778)

Select * from @table

Select      user_id,event_code,total_bookmarks,total_folders,folder_depth,ts
From        (
            Select      RANK() over (Partition by user_id
                                    Order by ts desc
                                    ) as Rank,
                        user_id,event_code,total_bookmarks,total_folders,folder_depth,ts

            From        @table
            ) D1
Where       D1.Rank = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多