SQL: “日终”选择

huangapple go评论127阅读模式
英文:

SQL: "End-of-day" select

问题

我有一个包含日期时间数据的表格(我正在使用Dremio)。对于表格中的所有列,我想选择给定日期的最后一条记录,例如对于日期2023-07-18,选择时间为10:30:23.537的行。

我尝试了SQL: Select the last record for each day given datetime中提出的解决方案。

我从上面的示例中删除了DATE参数,因为它会导致错误。

SELECT t1.* FROM t1

INNER JOIN
(
    SELECT Date_and_time AS Date_time, MAX(Date_and_time) AS Date_time_end
    FROM t1
    GROUP BY Date_and_time
) t2
    ON t2.Date_time = t1.Date_and_time AND
       t2.Date_time_end = t1.Date_and_time
ORDER BY
    t1.Date_and_time;

不幸的是,这没有给出结果,所有行都包含在结果表中。

英文:

I have a table, which contains some data with datetime in the below format (I'm using Dremio). For all columns in the table, I am trying to select only the last entry for a given day, e.g. for date 2023-07-18, row with time 10:30:23.537.

Date_and_time Parameter
2023-07-31 09:37:43.143 1
2023-07-18 10:30:23.537 2
2023-07-18 10:29:55.148 3
2023-07-10 09:43:32.187 4
2023-07-10 09:43:05.171 5
2023-07-10 09:42:36.498 6

I have tried the solution proposed in SQL: Select the last record for each day given datetime.

I removed the DATE parameter from the above example as it was giving errors.

SELECT t1.* FROM t1

INNER JOIN
(
    SELECT Date_and_time AS Date_time, MAX(Date_and_time) AS Date_time_end
    FROM t1
    GROUP BY Date_and_time
) t2
    ON t2.Date_time = t1.Date_and_time AND
       t2.Date_time_end = t1.Date_and_time
ORDER BY
    t1.Date_and_time;

Unfortunately, that has not given results as all rows were included in the result table.

答案1

得分: 1

这应该能解决问题

SELECT t2.castdate,
       t1.parameter
FROM table1 t1
JOIN
  (SELECT CAST(Date_and_time AS DATE) AS 'castdate',
          max(Date_and_time) AS 'Date_and_time'
   FROM table1
   GROUP BY castdate) t2 ON t1.Date_and_time = t2.Date_and_time

查询结果如下:

castdate parameter
2023-07-31 1
2023-07-18 2
2023-07-10 4
英文:

This should do the trick

SELECT t2.castdate,
       t1.parameter
FROM table1 t1
JOIN
  (SELECT CAST(Date_and_time AS DATE) AS 'castdate',
          max(Date_and_time) AS 'Date_and_time'
   FROM table1
   GROUP BY castdate) t2 ON t1.Date_and_time = t2.Date_and_time

Query results in

castdate parameter
2023-07-31 1
2023-07-18 2
2023-07-10 4

答案2

得分: 0

这可能对你有所帮助:

选择 * from table where date(Date_and_time)='2023-07-18' order by Date_and_time desc limit 1
英文:

This might help you :

select * from table where date(Date_and_time)='2023-07-18' order by Date_and_time desc limit 1

huangapple
  • 本文由 发表于 2023年8月9日 17:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定