嗨,我需要一點幫助,我的代碼,它幾乎是正確的,但只是一個小問題出錯。結果始於新年伊始開始
我有我的結果3列:
entries_per_week
它獲取新的項目,每星期所以 可能是5將每週3接下來的8下一等等。total_entries
它每週跟蹤總條目,所以它保持將'entries_per_week'列加起來 。- 然後
6WK_total
加起來前6周總。
所以基本上加起來就是previous_total_entries
中的6個。我幾乎有它的工作,但在新的一年開始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周總將是6所導致total_entries以前那麼這將是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|
+--------------+-------+-----------------------+-----------+
感謝