1

我正在尝试从我拥有的 MySQL 表中获取每周(如周一至周日,由 YEARWEEK 的 mode=1 参数指定)的股票值,其中包含每日最低价、最高价、开盘价和收盘价。

例如,以下查询正确地为我提供了 2012 年 1 月 1 日至 2012 年 3 月 1 日之间这周的高点和低点:

SELECT date, MIN(low), MAX(high) 
FROM daily_stock_values WHERE stock_id = SOMESTOCK 
AND date BETWEEN '2012-01-01' AND '2012-03-01' GROUP BY YEARWEEK(date, 1)

这正确输出:

+------------+-----------+-----------+
| date       | max(high) | min(low)  |
+-----------+-----------+-----------+
| 2012-01-01 | ......... | ......... |
| 2012-01-02 | ......... | ......... |
| 2012-01-09 | ......... | ......... |
| 2012-01-16 | ......... | ......... |
| 2012-01-23 | ......... | ......... |
| 2012-01-30 | ......... | ......... |
| 2012-02-06 | ......... | ......... |
| 2012-02-13 | ......... | ......... |
| 2012-02-20 | ......... | ......... |
| 2012-02-27 | ......... | ......... |
+------------+-----------+-----------+

如您所见,所有日期都正确指定(除了第一个是结果范围较低的日期)星期一,这是星期一至星期日的第一天。

但是,当我尝试介绍第一个和最后一个时(如此所述):

SELECT date, MIN(low), MAX(high),
SUBSTRING_INDEX(GROUP_CONCAT(CAST(open AS CHAR) ORDER BY date), ',', 1) AS open, 
SUBSTRING_INDEX(GROUP_CONCAT(CAST(close AS CHAR) ORDER BY date DESC), ',', 1) AS close
FROM daily_stock_values WHERE stock_id = SOMESTOCK 
AND date BETWEEN '2012-01-01' AND '2012-03-01' GROUP BY YEARWEEK(date, 1)

不幸的是,这弄乱了我的 GROUP BY 并导致日期不再与星期一对齐:

+------------+-----------+-----------+-----------+-----------+
| date       | max(high) | min(low)  | open      | close     |
+------------+-----------+-----------+-----------+-----------+
| 2012-01-01 | ......... | ......... | ......... | ......... |
| 2012-01-08 | ......... | ......... | ......... | ......... |
| 2012-01-15 | ......... | ......... | ......... | ......... |
| 2012-01-22 | ......... | ......... | ......... | ......... |
| 2012-01-29 | ......... | ......... | ......... | ......... |
| 2012-02-05 | ......... | ......... | ......... | ......... |
| 2012-02-12 | ......... | ......... | ......... | ......... |
| 2012-02-19 | ......... | ......... | ......... | ......... |
| 2012-02-26 | ......... | ......... | ......... | ......... |
| 2012-02-27 | ......... | ......... | ......... | ......... |
+------------+-----------+-----------+-----------+-----------+

这里发生了什么?谢谢!

4

2 回答 2

3

我能想出的最佳解决方案是:
SELECT YEARWEEK(date, 1) AS ignore, MIN(date) as date

这工作得很好!

于 2012-04-12T15:54:41.563 回答
0

实际上,您的第一个查询已经“搞砸了”。您正在选择日期并按周分组。这样想:如果您在同一周有两个日期,您希望显示什么日期?

您的选项是 select and group byYEARWEEK(date, 1)或 select and group by date

顺便说一句,您应该考虑提供有关它们包含的表和数据以及您的预期结果的更多信息。

于 2012-04-10T02:29:35.547 回答