出于性能原因,我需要创建按天计算的数据的物化视图。时间戳存储为UNIX时间戳。
为了允许更新(REPLACEing)到物化视图的表中,我希望它有一个时间戳,同样是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(时间戳)与当天的边界(24:00)相匹配,而不是最后一个聚合数据的时间戳?
答案 0 :(得分: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));
答案 1 :(得分: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');
上查看此代码