[英]SQL Select Last Timestamp of Each Day
I am trying to reduce a list of timestamps to only the last one from each day. 我正在尝试将时间戳列表减少到每天的最后一个。
I can use the following SQL to pull in the timestamps that I'm looking for but I'm also converting these to a formatted date, which I don't want to do. 我可以使用以下SQL提取所需的时间戳,但同时也将其转换为格式化的日期,我不想这样做。
select
from_unixtime(intTimeStamp) as day
from
(
select distinct intTimeStamp from TableA order by intTimeStamp desc
) as t2
group by
date(day)
order by
intTimeStamp desc
This is the output: 这是输出:
2014-08-29 13:21:01
2014-08-28 13:21:01
2014-08-27 13:21:01
2014-08-26 13:21:01
2014-08-25 13:21:21
2014-08-22 10:11:01
2014-08-21 13:21:01
2014-08-20 13:21:01
[remaining omitted]
This is as expected but I need them in their original unixtime format. 这是预期的,但我需要使用其原始的unixtime格式。
Simply removing the from_unixtime() function yields very odd behaviour, however. 但是,简单地删除from_unixtime()函数会产生非常奇怪的行为。 It only returns 6 rows , as opposed to the expected 168 .
它只返回6行 ,而不是预期的168行 。 I noticed that only one of the six rows returned is even the last timestamp for its day.
我注意到,返回的六行中只有一个甚至是当天的最后一个时间戳。 It's skipping 95% of the days with timestamps available but I'm not sure why.
可以跳过95%的时间戳,但我不确定为什么。
select
intTimeStamp as day
from
(
select distinct intTimeStamp from TableA order by intTimeStamp desc
) as t2
group by
date(intTimeStamp)
order by
intTimeStamp desc
This is the output: 这是输出:
1409343661
1409170501
1406060101
1401221701
1400271301
1400012101
EXPLAIN Output for both: 两者的解释输出:
1 PRIMARY <derived2> ALL 13338 Using temporary; Using filesort
2 DERIVED TableA range PRIMARY 4 10 Using index for group-by; Using temporary; Using filesort
How can I retrieve only the last timestamp from each day, as in the first query, but not have to convert them from a unix timestamp (or at least have them output as one)? 与第一个查询一样,如何才能每天只检索最后一个时间戳 ,而不必从unix时间戳转换它们(或至少将它们作为一个输出)?
Thanks. 谢谢。
You can do this with a simple group by
: 您可以通过一个简单的
group by
来做到这一点:
select max(intTimeStamp) as lasttimestamp
from TableA
group by date(from_unixtime(intTimeStamp))
order by lasttimestamp desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.