MySql在特定周内返回日期范围

时间:2012-06-26 09:28:09

标签: mysql

我可以使用下面的代码检索特定周内所有商品的总和/总销售额。

select week(real_pur_date) as week, itemcode, sum(quantity)
from sales
where week(real_pur_date) = week(20120620)
group by itemcode;

输出结果为:

+------+----------+---------------+
| week | itemcode | sum(quantity) |
+------+----------+---------------+
|   25 | KB001    |            11 |
|   25 | KB002    |             2 |
|   25 | KB003    |             3 |
+------+----------+---------------+

这就是我想要的

问题是如何查询MySql以将第25周中的日期范围返回到结果表中? 例如,
1.第24周的日期范围是10-06-2012至16-06-2012 2.第25周的日期范围是17-06-2012至23-06-2012。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我不是MySQL人,所以我不得不尝试从SQL Server函数转换。但是,基本的数学就在那里。我会告诉你如何传递或计算@YEARSTART和@YEAREND。

DECLARE @YEARSTART datetime, @YEAREND datatime
SET @YEARSTART='1/1/2012'
SET @YEAREND = '12/31/2012'

SELECT A.week, CASE WHEN (@YEARSTART + INTERVAL (8-DAYOFWEEK(@STARTYEAR)+(week-2)*7) DAY) < @YEARSTART 
                 THEN @YEARSTART
                 ELSE (@YEARSTART + INTERVAL (8-DAYOFWEEK(@STARTYEAR)+(week-2)*7) DAY) 
               END AS WeekStart,
               CASE WHEN (@YEARSTART + INTERVAL (7-DAYOFWEEK(@STARTYEAR)+(week-1)*7) DAY) > @YEAREND
                 THEN @YEAREND
                 ELSE (@YEARSTART + INTERVAL (7-DAYOFWEEK(@STARTYEAR)+(week-1)*7) DAY)
               END AS WeekEnd,
      A.itemcode, A.SumQty 
FROM
(
select week(real_pur_date) as week, itemcode, sum(quantity) AS SumQty
from sales
where week(real_pur_date) = week(20120620)
group by itemcode
) AS A