我希望将列amount
按自定义的每周日期范围分组,即每个星期一到星期日。
我的数据看起来像这样
date weekday amount
---------------|--------------|---------------
2015-03-01 sun 40
2015-03-02 mon 670
2015-03-03 tue 430
2015-03-04 wed 70
2015-03-05 thu 220
2015-03-06 fri 7
2015-03-07 sat 780
2015-03-08 sun 43
2015-03-09 mon 10
2015-03-10 tue 200
2015-03-11 wed 30
2015-03-12 thu 40
2015-03-13 fri 500
2015-03-14 sat 80
2015-03-15 sun 20
2015-03-16 mon 30
2015-03-17 tue 90
2015-03-18 wed 50
2015-03-19 thu 50
2015-03-20 fri 60
2015-03-21 sat 810
2015-03-22 sun 30
2015-03-23 mon 50
等,
等
我希望实现这样的目标
amount week
-----------|--------------------------------|---
2200 2015-03-02 - 2015-03-08
910 2015-03-09 - 2015-03-15
1120 2015-03-16 - 2015-03-22
或者,如果可能的话,这样会更好(如果没有,那么我只需将上述示例正则表示为新列)
amount date_start date_end
-----------|------------------|----------------|---
2200 2015-03-02 2015-03-08
910 2015-03-09 2015-03-15
1120 2015-03-16 2015-03-22
答案 0 :(得分:0)
预期的结果不会如下吗?如果没有,为什么不......
+------------+--------+
| date | amount |
+------------+--------+
| 2015-03-01 | 40 |40
+------------+--------+
| 2015-03-02 | 670 |
| 2015-03-03 | 430 |
| 2015-03-04 | 70 |
| 2015-03-05 | 220 |
| 2015-03-06 | 7 |
| 2015-03-07 | 780 |
| 2015-03-08 | 43 |2220
+------------+--------+
| 2015-03-09 | 10 |
| 2015-03-10 | 200 |
| 2015-03-11 | 30 |
| 2015-03-12 | 40 |
| 2015-03-13 | 500 |
| 2015-03-14 | 80 |
| 2015-03-15 | 20 |880
+------------+--------+
| 2015-03-16 | 30 |
| 2015-03-17 | 90 |
| 2015-03-18 | 50 |
| 2015-03-19 | 50 |
| 2015-03-20 | 60 |
| 2015-03-21 | 810 |
| 2015-03-22 | 30 |1120
+------------+--------+
| 2015-03-23 | 50 |50
+------------+--------+
假设我是对的,那么:
SELECT MIN(date) start
, MAX(date) end
, SUM(amount) total
FROM my_table
GROUP
BY YEARWEEK(date,1);
+------------+------------+-------+
| start | end | total |
+------------+------------+-------+
| 2015-03-01 | 2015-03-01 | 40 |
| 2015-03-02 | 2015-03-08 | 2220 |
| 2015-03-09 | 2015-03-15 | 880 |
| 2015-03-16 | 2015-03-22 | 1120 |
| 2015-03-23 | 2015-03-23 | 50 |
+------------+------------+-------+
答案 1 :(得分:0)
您可以尝试以下查询: -
SELECT SUM(amount) AS total, CONCAT(date, ' - ', date + INTERVAL 6 DAY) AS week
FROM Your_Table
GROUP BY WEEK(date, 1)
ORDER BY WEEK(date, 1)