MySQL get quantities from last 12 months grouped by month

。_饼干妹妹 提交于 2021-02-08 08:50:07

问题


I'm trying to write a MySQL SELECT statement in PHP.

I have 2 tables, sales and sale_items.

sales has columns: sale_id, status

sale_items has columns: sale_id, date_added (DATETIME), quantity

I need to return the quantities from sale_items, over the last 12 months grouped by month and where the status of the corresponding row in sales is equal to 'completed' (as you can see, sales and sale_items can be joined by sale_id).

I have tried modifying both of the following to suit my needs, but with no luck:

MySQL monthly Sale of last 12 months including months with no Sale

Mysql sum for last 12 months


回答1:


It's very easy you can use MySQL MONTH() function for this along with GROUP BY caluse.

SELECT SUM(SI.quantity),MONTH(SI.date_added)
FROM sale_items SI
JOIN sales S
ON S.id=SI.sale_id
WHERE S.status = 'completed'
GROUP BY MONTH(SI.date_added);



回答2:


SELECT COUNT(quantity),MONTH(SI.date_added)
FROM sale_items SI
JOIN sales S
ON S.id=SI.sale_id
WHERE S.status = 'completed'
GROUP BY MONTH(SI.date_added);


来源:https://stackoverflow.com/questions/39930771/mysql-get-quantities-from-last-12-months-grouped-by-month

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