0

出于性能原因,我需要创建按天汇总的数据的物化视图。时间戳存储为 UNIX 时间戳。

为了允许更新(替换)到物化视图的表中,我希望它有一个时间戳,再次采用 UNIX 时间戳格式,匹配一天的开始(或结束)。该时间戳将成为表键的一部分。每当基表数据更改时,我就可以仅更新该特定日期的视图表(再次为了性能)。

我当前的聚合语句如下所示:

REPLACE INTO aggregate_data (channel_id, type, timestamp, value)
SELECT channel_id, 'day' AS type, MAX(timestamp) AS timestamp, SUM(value) AS value
FROM data
GROUP BY channel_id, YEAR(FROM_UNIXTIME(timestamp/1000)), DAYOFYEAR(FROM_UNIXTIME(timestamp/1000));

如何使 MAX(timestamp) 匹配当天的边界 (24:00) 而不是最后一个聚合数据的时间戳?

4

2 回答 2

0

不确定我是否正确理解您的问题。你在寻找这样的东西吗?

REPLACE INTO aggregate_data (channel_id, type, timestamp, value)
SELECT channel_id, 'day' AS type, 

UNIX_TIMESTAMP(DATE_FORMAT(FROM_UNIXTIME(MAX(timestamp)), '%Y-%m-%d 23:59:59'))
AS timestamp, 

SUM(value) AS value
FROM data
GROUP BY channel_id, YEAR(FROM_UNIXTIME(timestamp/1000)), DAYOFYEAR(FROM_UNIXTIME(timestamp/1000));
于 2013-10-08T12:07:54.257 回答
0

无需使用 MAX,您只需使用 FROM_UNIXTIME() 即可将 unix 时间戳转换为特定日期。

REPLACE INTO aggregate_data (channel_id, type, timestamp, value)
SELECT channel_id, 
       'day' AS type, 
       FROM_UNIXTIME(timestamp, '%Y-%m-%d 00:00:00') AS timestamp, 
       SUM(value) AS value
FROM data
GROUP BY channel_id, FROM_UNIXTIME(timestamp, '%Y-%m-%d 00:00:00');

还要检查SQLFiddler上的此代码

于 2013-10-08T12:19:24.910 回答