嗨,我的代码需要一点帮助,它几乎是正确的,但只是出了点小问题。
我的结果中有 3 列:
entries_per_week
它每周都会获得新条目,因此可能有 5 个一周 3 下一个 8 下一个,依此类推。total_entries
它跟踪每周的总条目数,因此它不断增加“entries_per_week”列。- 然后将
6WK_total
前 6 周的总数加起来。
所以基本上加起来 6 个previous_total_entries
。我几乎让它工作了,但在新的一年6WK_total
开始时,从那一年开始新的开始,而不是把上一年的条目加起来。
这是我的代码:
SELECT a.*
, sum(b.total_entries) 6WK_total
FROM
( SELECT x.*
, SUM(y.entries_per_week) total_entries
FROM
( SELECT YEARWEEK(date_created) week_created
, COUNT(*) entries_per_week
FROM entries
GROUP
BY week_created
) x
JOIN
( SELECT YEARWEEK(date_created) week_created
, COUNT(*) entries_per_week
FROM entries
GROUP
BY week_created
) y
ON y.week_created <= x.week_created
GROUP
BY x.week_created
) a
JOIN
( SELECT x.*
, SUM(y.entries_per_week) total_entries
FROM
( SELECT YEARWEEK(date_created) week_created
, COUNT(*) entries_per_week
FROM entries
GROUP
BY week_created
) x
JOIN
( SELECT YEARWEEK(date_created) week_created
, COUNT(*) entries_per_week
FROM entries
GROUP
BY week_created
) y
ON y.week_created <= x.week_created
GROUP
BY x.week_created
) b
ON b.week_created BETWEEN a.week_created - (6 - 1) AND a.week_created
GROUP
BY week_created;
会发生什么,这里有一些结果,注意盯着 (**) 的结果,我想要的结果在另一个表的下方。它应该是 1056,如下面的期望结果表而不是 248
+--------------+-------+-----------------------+-----------+
| week_created | total | total_entries | 6WK_total |
+--------------+-------+-----------------------+-----------+
| 201149 | 49| 131 | 243 |
| 201150 | 37| 168 | 411 |
| 201151 | 37| 205 | 614 |
| 201152 | 18| 223 | 837 |
**| 201201 | 25| 248 | 248 |**
| 201202 | 33| 281 | 529 |
| 201203 | 66| 347 | 876 |
| 201204 | 70| 417 | 1293|
| 201205 | 61| 478 | 1771|
| 201206 | 88| 566 | 2337|
| 201207 | 72| 638 | 2727|
| 201208 | 72| 710 | 3156|
| 201209 | 67| 777 | 4030|
+--------------+-------+-----------------------+-----------+
所需的结果,请注意在 week_create '201206' 处,6 周总数将是 total_entries 中先前的 6 个结果,因此它将是 566 + 478 + 417 + 347 + 281 + 248 = 2337。
+--------------+-------+-----------------------+-----------+
| week_created | total | total_entries | 6WK_total |
+--------------+-------+-----------------------+-----------+
| 201149 | 49| 131 | 243 |
| 201150 | 37| 168 | 411 |
| 201151 | 37| 205 | 614 |
| 201152 | 18| 223 | 837 |
| 201201 | 25| 248 | 1056|
| 201202 | 33| 281 | 1256|
| 201203 | 66| 347 | 1472|
| 201204 | 70| 417 | 1127|
| 201205 | 61| 478 | 1989|
| 201206 | 88| 566 | 2337|
| 201207 | 72| 638 | 2727|
| 201208 | 72| 710 | 3156|
| 201209 | 67| 777 | 4030|
+--------------+-------+-----------------------+-----------+
谢谢