gpt4 book ai didi

MySQL 去年同一天

转载 作者:行者123 更新时间:2023-11-29 08:58:41 26 4
gpt4 key购买 nike

除了关于周开始/结束的争论之外,如何获得从同一个表中选择的查询来比较本周与去年同一周的数字?

每次我尝试时,数字都会被夸大,因为它正在执行跨产品类型的操作。

类似

SELECT 
DATE(t1.`date`) AS 'Date', SUM(t1.`sold`), SUM(t2.`sold`)
FROM `table` AS t1
JOIN `table` AS t2 ON WEEK(t1.`date`) = WEEK(t2.`date`)
WHERE WEEK(t1.`date`) = WEEK(CURDATE()) AND YEAR(t1.`date`) = YEAR(CURDATE()) AND YEAR(t2.`date`) = YEAR(DATE_ADD(NOW(), INTERVAL - 1 YEAR))
GROUP BY DATE(t1.`date`)

最佳答案

下面这个怎么样?

mysql> SELECT * FROM test;
+------------+------+
| date | sold |
+------------+------+
| 2012-02-10 | 100 |
| 2012-02-10 | 200 |
| 2011-02-10 | 50 |
| 2011-02-10 | 25 |
+------------+------+
4 rows in set (0.00 sec)

mysql> SELECT
-> CONCAT(WEEK(date), "-", YEAR(date)), SUM(sold)
-> FROM
-> test
-> WHERE
-> WEEK(`date`) = WEEK(NOW())
-> AND (YEAR(`date`) = YEAR(NOW()) OR YEAR(`date`) = YEAR(DATE_ADD(NOW(), INTERVAL - 1 YEAR)))
-> GROUP BY
-> YEAR(date), WEEK(date);
+-------------------------------------+-----------+
| CONCAT(WEEK(date), "-", YEAR(date)) | SUM(sold) |
+-------------------------------------+-----------+
| 6-2011 | 75 |
| 6-2012 | 300 |
+-------------------------------------+-----------+
2 rows in set (0.00 sec)

关于MySQL 去年同一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com