mysql查询 - 查找与给定日期范围匹配的列

时间:2013-01-20 20:43:58

标签: mysql left-join

好吧,我搜索了帖子,但找不到我正在尝试的具体查询的答案。我有一个非常简单的表:

mysql> DESCRIBE offpeak_mccavg_raw;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| date  | date         | YES  |     | NULL    |       |
| node  | varchar(30)  | YES  |     | NULL    |       |
| price | decimal(6,4) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

每天,给定节点和给定价格大约有1700个条目(注意,在下面的例子中,日期不是连续的。我一直在测试一些东西,所以这就是日期偏离的原因。通常情况下,每天都会有参赛作品。)

mysql> select * from offpeak_mccavg_raw order by node limit 10;
+------------+---------------+---------+
| date       | node          | price   |
+------------+---------------+---------+
| 2012-01-08 | AEC           | -0.4083 |
| 2013-01-18 | AEC           |  1.2125 |
| 2013-01-18 | AECI          | -1.7575 |
| 2012-01-08 | AECI          | -1.2488 |
| 2013-01-18 | AECI.ALTW     | -5.0950 |
| 2012-01-08 | AECI.ALTW     | -6.3258 |
| 2013-01-18 | AECI.AMMO     | -0.4725 |
| 2012-01-08 | AECI.AMMO     | -0.8117 |
| 2013-01-18 | AECI.APM_1.AZ | -0.9088 |
| 2012-01-08 | AECI.APM_1.AZ | -0.7729 |
+------------+---------------+---------+

我正在尝试在给定的日期范围内找到每天具有相同价格的节点对。如果我只有1天的数据,我已经能够编写一个查询,找到与给定日期匹配的对 - 但不是在一天的范围内。理想情况下,我想运行一个查询,显示过去2周,2个月等所有符合价格的节点对。

以下是适用于特定日期的查询:

SELECT b1.node, b2.node FROM onpeak_mccavg_raw AS b1 LEFT JOIN onpeak_mccavg_raw AS b2 ON b1.price = b2.price WHERE b1.node < b2.node;

我试图扩展WHERE子句并添加日期范围,但它不起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

SELECT   b1.node, b2.node
FROM     onpeak_mccavg_raw b1
    JOIN onpeak_mccavg_raw b2
      ON b1.date = b2.date
     AND b1.node < b2.node
GROUP BY b1.node , b2.node
HAVING   SUM(b1.price = b2.price) = COUNT(*)