一尘不染

mysql按周分组

sql

我有一个包含以下字段的表:

  • ID
  • amount_sale
  • the_date(unix时间戳整数)
  • payment_type(可以是现金,也可以是帐户)

我正在尝试创建一个查询,该查询将按一年中的每个星期对所有销售额进行分组,然后在我的页面上对每个星期的amount_sales总和进行拆分。

例子:

week 1 = $26.00  
week 2 = $35.00  
week 3 = $49.00

等等。我正在使用此查询,但它不起作用:

  SELECT SUM(`amount_sale`) as total 
    FROM `sales` 
   WHERE `payment_type` = 'Account' 
GROUP BY WEEK(`the_date`)

阅读 170

收藏
2021-03-17

共1个答案

一尘不染

如果存储the_date为整数,则首先需要使用FROM_UNIXTIME函数将其转换为日期时间:

 SELECT SUM(`amount_sale`) as total 
FROM `sales` 
WHERE `payment_type` = 'Account' 
GROUP BY WEEK(FROM_UNIXTIME(`the_date`))

UPDATE
另外,您可能要输出周数,

SELECT CONCAT('Week ', WEEK(FROM_UNIXTIME(`the_date`))) as week_number,
SUM(`amount_sale`) as total 
FROM `sales` 
WHERE `payment_type` = 'Account' 
GROUP BY WEEK(FROM_UNIXTIME(`the_date`))
2021-03-17