mysql grouping by week

二次信任 提交于 2019-11-30 07:15:38

If you store the_date as integer, you first need to convert it to datetime using FROM_UNIXTIME function:

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

UPDATE:
Also, you might want to output week number,

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`))

Try to also select the weeks in your query, like this:

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

If you have weeks covering several years you could also select the year from the_date and order on that as well, like

  ORDER BY week ASC, year ASC

Since the_date is a unix timestamp, the WEEK function won't work. Instead, you can do this:

GROUP BY week(FROM_UNIXTIME(the_date))

Keep in mind, this will not perform well, as that function will need to be applied to every row in the table you're querying.

Limey

take your date and get the week:

SELECT DATEPART( wk, getdate())  --this is assuming SQL server

and then group on that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!