MySQL去年同一天

时间:2012-02-10 05:51:21

标签: mysql sql

关于周开始/结束的争论,你怎么得到一个从同一个表中选择的查询来比较本周与去年同一周的数字?

每次尝试时,数字都会膨胀,因为它正在做一个跨产品类型的东西。

这样的东西
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`)

2 个答案:

答案 0 :(得分:2)

以下情况如何?

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)

答案 1 :(得分:0)

我推荐@ MartinJansen的答案 - 当你只想提取一个特定的星期时,MySQL的行比列式更好,特别是

但是,如果你想按列进行,或者如果你想要它超过一个特定的一周,你可以尝试:

mysql> SELECT * from sales;
+------------+------+
| date       | sold |
+------------+------+
| 2011-01-01 |    1 |
| 2011-01-02 |   10 |
| 2011-01-03 |    3 |
| 2012-01-01 |   10 |
| 2012-01-02 |   20 |
+------------+------+

SELECT CONCAT('week',WEEK(t.`date`)) as week, 
 SUM(IF(YEAR(t.`date`)=YEAR(DATE_ADD(NOW(), INTERVAL - 1 YEAR)),t.sold,0)) as `2011`, 
 SUM(IF(YEAR(t2.`date`)=YEAR(NOW()),t2.sold,0)) as `2012`
FROM sales t
LEFT JOIN sales t2
ON t.date = t2.date     --could add WHERE WEEK(t.date)=... to restrict week
GROUP BY WEEK(t.date)

+-------+------+------+
| week  | 2011 | 2012 |
+-------+------+------+
| week0 |    1 |    0 |
| week1 |   13 |   30 |
+-------+------+------+

(你必须阅读MySQL对周的确切定义)。