问题
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