GROUP BY从特定日期时间开始?

时间:2012-05-23 19:31:52

标签: mysql group-by aggregate

我正在尝试对观察表中的结果进行分组。 我的表每隔几秒就包含一次库存值。 我希望能够每2小时,4小时8小时等显示有关股票的汇总信息,但我需要这些时段从下午5点开始。 例如,如果数据从2012-05-23 17:45:34开始,则第一次观察将从23日的17:00:00到23日的19:00:00,依此类推。 我可以根据时间间隔对数据进行分组,但我不知道如何在下午5点开始设置..

1 个答案:

答案 0 :(得分:0)

为什么不在where子句中添加条件。花时间(从您的日期时间)并检查以确保它大于17:00:00。如果是在下午5点之前,则不要在计算中使用它。

编辑您提到您已完成分组。如何在你的where子句中添加子查询的最后一天下午5点开始(不确定语法):

where datetimeCol >= (select min(date(datetimeCol) + time(5pm)) from tableUsed where previousUsedConditions or id = outerTable.Id)

修改

我知道你有一个更复杂的分组但是(在tsql中)这是我在使用where语句时的想法。

declare @tempTable table (mydate smalldatetime)
insert into @tempTable 
    values('2012-05-23 04:37:04.900'),
        ('2012-05-23 18:37:04.900'),
        ('2012-05-24 04:37:04.900'),
        ('2012-05-25 05:37:04.900')     

select * 
from @tempTable as tbl
group by mydate 

select (cast(cast((select min(temp.myDate) from @tempTable as temp) as DATE) as datetime) + cast(cast( '17:00:00.0000000' as time)as datetime))  as 'This is the time that is getting filtered by below'

select * 
from @tempTable as tbl
where tbl.mydate > (cast(cast((select min(temp.myDate) from @tempTable as temp) as DATE) as datetime) + cast(cast( '17:00:00.0000000' as time)as datetime)) 

这给出了以下结果:

(4 row(s) affected)
mydate
-----------------------
2012-05-23 04:37:00
2012-05-23 18:37:00
2012-05-24 04:37:00
2012-05-25 05:37:00

(4 row(s) affected)

This is the time that is getting filtered by below
--------------------------------------------------
2012-05-23 17:00:00.000

(1 row(s) affected)

mydate
-----------------------
2012-05-23 18:37:00
2012-05-24 04:37:00
2012-05-25 05:37:00

(3 row(s) affected)