1

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

Community
  • 1
  • 1
sgspragg
  • 19
  • 6

2 Answers2

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);
Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0
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);
MounirOnGithub
  • 669
  • 1
  • 9
  • 22
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – andreas Oct 08 '16 at 10:21
  • Ok I will explane more next time sorry. – MounirOnGithub Oct 08 '16 at 11:19