2

我在 MySQL 中有两个表。在这些表中的每一个中,都保存了设备及其 MAC 地址和状态区域信息。

这些状态确实在某些时间戳(startTime,endTime)及其持续时间(endTime-startTime)开始和结束,并且是由某些 id 引起的。

现在我想找到以天分隔的某些事件“移动”和“加载”之间的重叠,如下所示:

sum of time, when movement took place (value in the fiddle: 421)
sum of time, when load took place (value in the fiddle: 520)
sum of time, when movement and load took place (value in the fiddle: 391)

查询结果应如下所示:

ID                  DATE                            ALL_MOVEMENT    ALL_LOAD    LOAD_MOVEMENT
00:50:c2:63:10:1a   October, 29 2012 00:00:00+0000  421             520         391
00:50:c2:63:10:1a   February, 22 2013 00:00:00+0000 421             520         391
00:50:c2:63:10:1b   February, 22 2013 00:00:00+0000 181             220         181

我在这里准备了一个小提琴:http ://sqlfiddle.com/#!2/c210c

更新:在这里可以看到在不同的表结构中提供我想要的东西的小提琴:

http://sqlfiddle.com/#!2/31b94/1

4

2 回答 2

4

我真的不明白数据集与结果集的相关性,但在我看来,你或多或少想要这样的东西......

 SELECT m.id
      , DATE(FROM_UNIXTIME(m.starttime))Date,SUM(m.duration) all_movement
      , SUM(l.duration) all_load
   FROM move_table m
   JOIN load_table l
     ON l.id = m.id
    AND l.endtime > m.starttime
    AND l.starttime < m.endtime
  GROUP 
     BY m.id
      , DATE(FROM_UNIXTIME(m.starttime));
 +-------------------+------------+--------------+----------+
 | id                | Date       | all_movement | all_load |
 +-------------------+------------+--------------+----------+
 | 00:50:c2:63:10:1a | 2012-10-29 |          391 |      520 |
 | 00:50:c2:63:10:1a | 2013-02-22 |          391 |      520 |
 | 00:50:c2:63:10:1b | 2013-02-22 |          181 |      220 |
 +-------------------+------------+--------------+----------+

顺便说一句,duration在这种情况下似乎是多余的,因为(例如) SUM(m.endtime-m.starttime) 会得到相同的结果。

于 2013-03-14T12:05:26.980 回答
3

我不知道如何解决“加载”和“无加载”之间的区别,因为数据库中没有关于它的真实信息 - 但也许这是您尝试的起点。

SELECT a.ID, a.D, SUM(a.MOVETIME) AS ALL_MOVEMENT, SUM(a.LOADTIME) AS ALL_LOAD
FROM (
SELECT ID, DATE(FROM_UNIXTIME(startTime)) AS d, SUM(duration) AS MOVETIME, 0 AS LOADTIME
FROM move_table
GROUP BY ID, DATE(FROM_UNIXTIME(startTime))
UNION
SELECT ID, DATE(FROM_UNIXTIME(startTime)) AS d, 0 AS MOVETIME, SUM(duration) AS LOADTIME
FROM load_table
GROUP BY ID, DATE(FROM_UNIXTIME(startTime))) AS a
GROUP BY a.ID, a.D
于 2013-03-14T11:55:58.643 回答