【问题标题】:Select max value of timestamp grouped by name, jobId and Action [duplicate]选择按名称,jobId和Action分组的时间戳的最大值[重复]
【发布时间】:2021-02-18 23:50:57
【问题描述】:

我的表格如下所示(在图像的上半部分),我想选择user 执行的工作的max timestamp。例如,User1 执行了许多Process1 活动,我们需要在5.11.2020 上为Process1 选择最新的活动Start

我不能使用group by,因为我会在selectgroup by 中包含所有列名,因为时间戳对于每个员工都是唯一的,因此只会获取所有列名。

我怎样才能做到这一点?

样本数据:

| User  | Activity | Timestamp       | Action |
|-------|----------|-----------------|--------|
| User1 | process1 | 1.11.2020 10:00 | Start  |
| User1 | process1 | 1.11.2020 10:30 | Stop   |
| User1 | process1 | 1.11.2020 11:00 | Start  |
| User1 | process1 | 1.11.2020 11:30 | Start  |
| User1 | process1 | 5.11.2020 10:00 | Start  |
| User2 | process1 | 5.11.2020 10:05 | Start  |
| User2 | process1 | 5.11.2020 10:30 | Stop   |
| User2 | process2 | 5.11.2020 10:45 | Start  |

输出应该是:

| User  | Activity | LastAction |
|-------|----------|------------|
| User1 | process1 | Start      |
| User2 | process1 | Stop       |
| User2 | process2 | Start      |

【问题讨论】:

  • 提问时请提供可消费的数据库结构和示例数据。屏幕截图不是很有帮助。此外,请提供您迄今为止尝试过的信息!但是,看看窗口函数(例如ROW_NUMBER() OVER (PARTITION BY... ORDER BY...) - 这应该可以解决问题

标签: sql sql-server datetime greatest-n-per-group


【解决方案1】:

您可以使用row_number() 来识别每个用户和活动的最新行:

select *
from (
    select t.*,
        row_number() over(partition by user, activity order by timestamp desc) rn
    from mytable t
) t
where rn = 1

【讨论】:

    猜你喜欢
    • 2013-06-22
    • 1970-01-01
    • 2011-07-14
    • 2020-10-27
    • 1970-01-01
    • 2016-03-23
    • 2023-03-12
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多