我们有一个如下表所示的内容,
Timestamp | Total_Value
2015-06-05 07:14:23 ------------568
2015-06-06 15:14:23 ------------768
2015-06-07 15:14:23 ------------868
2015-06-08 19:47:30 ------------968
2015-06-30 19:47:30 ------------1668
2015-07-01 06:47:30 ------------268
班次从当天早上7点开始到第二天早上7点。总共三班倒。因此,每天数据计算需要第二天的数据,直到上午7点。
SELECT DAY(TIMESTAMP) AS DAY, MAX(Total_Value) AS `Total`
FROM Table_NAME
WHERE MONTH(TIMESTAMP) = MONTH(NOW())
GROUP BY DAY(TIMESTAMP)
ORDER BY DAY
以上查询为2015-06-01 00:00:00至2015-06-30 23:59:59之间的时间戳正确提供个别日期的数据
但是我需要2015-06-01 07:00:00到2015-07-01 06:59:59之间的一个月的数据
Day --------Total_Value
1 ------------0
2 ------------0
3 -------------0
4 -------------0
5 ------------568
6 ------------768
7 ------------868
8 ------------968
.
.
.
.
30 ------------1768
2)还需要MySQL查询将一天分为3班,其中班次为7:00至3:30 PM,3:30 PM至11:00 PM和11 PM至7:00 AM(第二天),并将其分组为a周。
请帮助解决此问题。提前谢谢。
答案 0 :(得分:0)
从时间戳减去7个小时,将其调整到适当的班次。
SELECT DAY(DATE_SUB(timestamp, INTERVAL 7 HOUR)) AS Day, MAX(total_value) AS Total
FROM Table_Name
WHERE MONTH(DATE_SUB(timestamp, INTERVAL 7 HOUR)) = MONTH(NOW())
GROUP BY Day
ORDER BY Day
要将其分解为班次,请使用CASE
表达式确定班次
SELECT DAY(DATE_SUB(timestamp, INTERVAL 7 HOUR)) AS Day,
CASE WHEN DATE_FORMAT(timestamp, '%H:%i') < '07:00' THEN 3
WHEN DATE_FORMAT(timestamp, '%H:%i') < '15:30' THEN 1
WHEN DATE_FORMAT(timestamp, '%H:%i') < '23:00' THEN 2
ELSE 3
END AS Shift,
MAX(total_value) AS Total
FROM Table_Name
WHERE MONTH(DATE_SUB(timestamp, INTERVAL 7 HOUR)) = MONTH(NOW())
GROUP BY Day, Shift
ORDER BY Day, Shift