(Mysql)按日期时间范围合并两个表

时间:2017-11-21 11:26:36

标签: mysql join dataframe

有两个表,第一个表有start&结束日期。

+----+------------+------------+
| id |    start   |     end    | 
+----+------------+------------+
|  a | 2016-07-10 | 2016-07-12 |
|  a | 2016-07-12 | 2016-07-18 |
|  a | 2016-07-20 | 2016-07-24 |
|  b | 2016-07-11 | 2016-07-15 |
|  b | 2016-07-17 | 2016-07-20 |
+----+------------+------------+

我想加入的是下表。

+----+------------+------------+------------+
| id |    count   |    pno     |     date   | 
+----+------------+------------+------------+
|  a |     1      |     1      | 2016-07-12 |
|  a |     1      |     1      | 2016-07-15 |
|  a |     0      |     1      | 2016-07-16 |
|  a |     1      |     1      | 2016-07-17 |
|  b |     0      |     1      | 2016-07-12 |
|  b |     1      |     1      | 2016-07-13 |
|  b |     1      |     1      | 2016-07-14 |
+----+------------+------------+------------+

我想得到的结果是

+----+------------+------------+------------+------------+
| id |    start   |     end    |  per_pno   |  per_count |
+----+------------+------------+------------+------------+
|  a | 2016-07-10 | 2016-07-12 |      1     |      1     |
|  a | 2016-07-12 | 2016-07-18 |      3     |      2     |
|  a | 2016-07-20 | 2016-07-24 |      0     |      0     |
|  b | 2016-07-11 | 2016-07-15 |      3     |      2     |
|  b | 2016-07-17 | 2016-07-20 |      0     |      0     |
+----+------------+------------+------------+------------+

因为你可以看到计数,pno在每个时段之间起作用。结束日期和'id'条件......

解决起来似乎非常困难。

2 个答案:

答案 0 :(得分:2)

您可以加入这两个表,条件是第二个表中的日期位于第一个表中给定记录的范围之间,id在两个表中都匹配。然后,聚合第一个表中的每一行以获得总计。请注意,连接条件有点棘手,因为您的范围可以在同一日期结束并开始。因此,连接条件确保我们不会重复计算天数。

SELECT
    t1.id,
    t1.start,
    t1.end,
    COALESCE(SUM(t2.pno), 0)   AS per_pno,
    COALESCE(SUM(t2.count), 0) AS per_count
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.id = t2.id AND
       t2.date > t1.start AND t2.date <= t1.end
GROUP BY
    t1.id, t1.start, t1.end
ORDER BY
    t1.id, t1.start;

enter image description here

Demo

答案 1 :(得分:1)

使用此查询

SELECT tbl1.start1 as start1, tbl1.end1 as end1, sum(tbl2.count1) as countq, sum(tbl2.pno) as pno FROM tbl1 LEFT JOIN tbl2 ON (tbl2.date1 BETWEEN tbl1.start1 AND tbl1.end1) WHERE 1=1 GROUP BY tbl1.id