MySQL Query来计算上周

时间:2009-07-16 15:07:16

标签: mysql

我想计算上周的总订单金额。

我收到了从当前日期获取过去7天数据的查询。

SELECT SUM(goods_total) AS Total_Amount  FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 7 day);

现在我怎样才能获得上周的数据,不包括本周。

例如本周我赚了15,000美元,上周我赚了14,000美元。

我通过运行上述查询得到15,000美元。

但我不知道如何计算前一周。

8 个答案:

答案 0 :(得分:5)

根据您在Alex的答案中提供的其他信息,我猜以下内容可能有效:

SELECT SUM(goods_total) AS Total_Amount, "Previous week" AS Week FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 14 day) 
AND order_placed_date < date_sub(current_date, INTERVAL 7 day)
UNION
SELECT SUM(goods_total) AS Total_Amount, "This week" AS Week FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 7 day) 

这应该返回两行和两列,每周的总金额。

答案 1 :(得分:3)

前8到14天的记录不包括最近7天的记录,查询:

SELECT * FROM `Table_Name` 
WHERE `Field_Name` >= DATE_SUB(NOW(),INTERVAL 14 DAY) 
AND `Field_Name` < DATE_SUB(NOW(),INTERVAL 7 DAY)
  • Field_Name:必须是YYYY-mm-dd格式的有效日期(2012-09-20)。
  • Table_Name:您需要从哪里获取记录。

答案 2 :(得分:2)

如果您想要“滚动周”(滑动7天长的窗口)而不是周日(或其他特定工作日)开始的几周,

SELECT SUM(goods_total) AS Total_Amount FROM orders
WHERE order_placed_date BETWEEN
 date_sub(current_date, INTERVAL 14 day) AND
 date_sub(current_date, INTERVAL 8 day);

答案 3 :(得分:0)

您可以使用DATE_SUB()

答案 4 :(得分:0)

尝试:

SELECT SUM(goods_total) AS Total_Amount  FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 14 day) 
AND order_placed_date < date_sub(current_date, INTERVAL 7 day);

答案 5 :(得分:0)

以下查询如何:

SELECT   count(order_placed_date) 
FROM     orders
WHERE    YEARWEEK(order_placed_date) = YEARWEEK(CURRENT_DATE - INTERVAL 7 DAY) 

答案 6 :(得分:0)

mysql> SELECT DATE_SUB(current_date, INTERVAL WEEKDAY(current_date)+8 DAY) last_sunday
, YEARWEEK(DATE_SUB(current_date, INTERVAL WEEKDAY(current_date)+8 DAY)) last_week_of_year
, DATE_SUB(current_date, INTERVAL WEEKDAY(current_date)+1 DAY) this_sunday
, YEARWEEK(DATE_SUB(current_date, INTERVAL WEEKDAY(current_date)+1 DAY)) this_week_of_year;

*************************** 1. row ***************************
      last_sunday: 2012-01-29
last_week_of_year: 201205
      this_sunday: 2012-02-05
this_week_of_year: 201206

答案 7 :(得分:-1)

最简单的方法是使用mysql Date and Time Functions

WEEKOFYEAR()