使用日期时间获取最新

问题描述 投票:0回答:2

我有下表 -

| Table      | Status     | Code   | Timestamp
| --------   | ---------  | ------ | ---------------
| Budget     | Success    | access | 03-02-2024T08:04:23.19Z
| Property   | Failed     | access | 03-02-2024T08:04:23.19Z
| Transfer   | Success    | access | 03-02-2024T08:04:23.19Z
| Property   | Success    | access | 03-02-2024T08:04:23.19Z
| Load       | Success    | access | 03-02-2024T00:07:02.54Z
| Property   | Failed     | access | 03-02-2024T00:07:02.54Z
| Transfer   | Success    | uprow  | 03-02-2024T00:07:02.54Z
| Load       | Success    | uprow  | 01-02-2024T18:17:54.42Z
| Property   | Failed     | uprow  | 01-02-2024T18:17:54.42Z
| Transfer   | Success    | uprow  | 01-02-2024T18:17:54.42Z

我想要每个表的最近时间戳,其中代码是“访问”。这与状态无关。请建议一个sql查询。

| Table      | Status     | Code   | Timestamp
| --------   | ---------  | ------ | ---------------
| Budget     | Success    | access | 03-02-2024T08:04:23.19Z
| Property   | Failed     | access | 03-02-2024T08:04:23.19Z
| Transfer   | Success    | access | 03-02-2024T08:04:23.19Z
| Load       | Success    | access | 03-02-2024T00:07:02.54Z
sql
2个回答
0
投票

如果我正确理解你的问题,你想根据时间戳获取表中的所有条目。

这是一个 mysql 解决方案,如果您需要其他 SQL 语言,请告诉我们并更改您的帖子标签。

要按代码为 Table 的每个唯一

access
最近时间戳
对结果进行排序,您可以创建以下 SQL 查询以包含
ORDER BY
子句:

SELECT Content, MAX(Timestamp) AS recent_timestamp FROM your_table_name
WHERE Code = 'access' ORDER BY recent_timestamp DESC;

0
投票

这应该适用于大多数现代数据库:

WITH Numbered AS (
    select "Table", Status, Code, Timestamp
        , row_number() over (partition by "Table" order by Timestamp desc) rn
    from "MyTable"
    where Code = 'access'
)
SELECT "Table", Status, Code, Timestamp
FROM Numbered
WHERE rn = 1
ORDER BY Timestamp DESC

但要小心:一些仍然常用的数据库可能看起来很现代,但实际上并不符合现代标准,例如 Access 或 MySQL 5.7。

您可以在此处看到它适用于任何受支持的关联数据库版本:

它们之间的唯一区别是

TimeStamp
列的数据类型,MySQL 不会使用 ANSI 对象分隔符。

但请告诉我们您下次使用的数据库,因为差异通常更显着。

© www.soinside.com 2019 - 2024. All rights reserved.