SQL / PHP如何从每天的同一时间开始连续编号

时间:2016-06-22 18:17:51

标签: php sql

我正在试图弄清楚如何累计“条目” - 退出'每周的每个小时,每周同一时间。即每个星期二下午12点,每个星期二下午1点退出多少个条目。

${'request'.'$i'} = "SELECT starttime AS time, SUM(enters-exits) as
  entries FROM DEV_DoorCam WHERE (CAST( starttime AS date )='$startDate' 
  AND CAST( starttime AS time )>='07:00:00' AND (zone_name='Entrance' OR
  zone_name='SideDoor')) GROUP BY (UNIX_TIMESTAMP(starttime)) DIV 
  '".(int)$divisor."';";
try{    
    ${'result'.'$i'} = mysqli_query($conn, ${'request'.'$i'});
....
while ($row = mysqli_fetch_assoc(${'result'.'$i'})) {
        ${"DataSet".$i}[$row["time"]] = $row["entries"];
....
foreach(${"DataSet".$i} as $time => $entries){
        file_put_contents('mydata.txt', $time, FILE_APPEND | LOCK_EX);
        file_put_contents('mydata.txt', "   ", FILE_APPEND | LOCK_EX);
        file_put_contents('mydata.txt', $entries, FILE_APPEND | LOCK_EX);
        file_put_contents('mydata.txt', "\n", FILE_APPEND | LOCK_EX);
    }       

这给了我以下

2016-06-17 07:00:00   8  //between 7 and 8 there are 8 more entries than exits
2016-06-17 08:00:00   8
2016-06-17 09:00:00   14
2016-06-17 10:00:00   2
2016-06-17 11:00:00   6
2016-06-17 12:00:00   0
2016-06-17 13:00:00   12
2016-06-17 14:00:00   9
2016-06-17 15:00:00   7
2016-06-17 16:00:00   -2
2016-06-17 17:00:00   0
2016-06-17 18:00:00   -9
2016-06-17 19:00:00   -2
2016-06-17 20:00:00   -5
2016-06-17 21:00:00   0
2016-06-17 22:00:00   0
2016-06-17 23:00:00   0

2016-06-18 07:00:00   7
2016-06-18 08:00:00   3
2016-06-18 09:00:00   11
2016-06-18 10:00:00   6
2016-06-18 11:00:00   8
2016-06-18 12:00:00   4
2016-06-18 13:00:00   -12
2016-06-18 14:00:00   5
2016-06-18 15:00:00   -7
....
....

如何将它们分组到每个星期二的7.00到8.00

使用(Ta Parfait)

SELECT DAYNAME(starttime) AS DayOfWeek, TIME(starttime) As TimeOfDay, 
SUM(enters-exits) as entries FROM DEV_DoorCam WHERE 
DAYOFWEEK(starttime)=1 AND TIME(starttime) >= '07:00:00' AND 
(zone_name='Entrance' OR zone_name='SideDoor') GROUP BY  
(UNIX_TIMESTAMP(starttime) DIV 3600) ORDER BY TIME(starttime);

我得到了

Sunday  07:00:00    21
Sunday  07:00:00    -2
Sunday  07:00:00    2
Sunday  08:00:00    3
Sunday  08:00:00    28
Sunday  08:00:00    -6
Sunday  09:00:00    0
Sunday  09:00:00    6
Sunday  09:00:00    15

我想要的是

Sunday  07:00:00    21
Sunday  08:00:00    25
Sunday  09:00:00    21

1 个答案:

答案 0 :(得分:0)

考虑在聚合查询中使用MySQL的Date and Time functions,特别是DAYNAME()TIME() starttime进行分组:

SELECT DAYNAME(starttime) AS DayOfWeek, 
       TIME_FORMAT(TIME(starttime), '%H:00:00') As TimeOfDay, 
       SUM(enters-exits) as entries 
FROM DEV_DoorCam 
WHERE (TIME(starttime) >= '07:00:00') 
AND   (zone_name='Entrance' OR zone_name='SideDoor')
GROUP BY DAYNAME(starttime), 
         TIME_FORMAT(TIME(starttime), '%H:00:00')

如果您特别需要星期二,请添加到WHERE子句:

AND DAYNAME(starttime) = 'Tuesday'

OR

AND DAYOFWEEK(starttime) = 3