mysql grouping by week

懵懂的女人 提交于 2019-11-29 09:25:20

问题


I have a table with the following fields:

  • id
  • amount_sale
  • the_date (unix timestamp integer)
  • payment_type (can be Cash, or Account)

I am trying to create a query that will group all sales by each week of the year, and then split the sum of amount_sales for each week on my page.

Example:

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

etc. I'm using this query but it's not working:

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

回答1:


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



回答2:


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



回答3:


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.




回答4:


take your date and get the week:

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

and then group on that.



来源:https://stackoverflow.com/questions/6710342/mysql-grouping-by-week

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