我试图每周抓一张(就像在Mon-Sun中,由yEARWEEK的mode = 1参数指定)来自MySQL表格中的股票价值,每日低价,高价,开盘价和收盘价。
例如,以下查询正确地给出了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 | ......... | ......... |
+------------+-----------+-----------+
正如您所看到的,所有日期都正确指定(除了第一个结果的较低范围之外)星期一,也就是星期一太阳星期的第一天。
然而,当我尝试引入第一个和最后一个(如所描述的here)时:
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 | ......... | ......... | ......... | ......... |
+------------+-----------+-----------+-----------+-----------+
这里发生了什么?谢谢!
答案 0 :(得分:3)
我能想出的最佳解决方案是:
SELECT YEARWEEK(date, 1) AS ignore, MIN(date) as date
这很有效!
答案 1 :(得分:0)
实际上,您的第一个查询已经“搞砸了”。您按周选择日期和分组。这样想:如果你在同一周有两个日期,你期望什么日期显示?
您的选择是按YEARWEEK(date, 1)
选择和分组,或者按date
选择和分组。