tags:

views:

38

answers:

2

I have two tables, sales and costs, each with a costs fields, and a date field of type date.

The rest of the fields are not relevant for what I want to do.

I want to take the totals of each month, and display them together.

I am unsure if most of this should be done in SQL, if it must be one or several queries, of if I must manipulate the data in PHP...

A: 

You can achieve this with SUM() and GROUP BY in sql

Redlab
+1  A: 

Try this two queries for each table.

SELECT month(date_field), SUM(cost_field)
FROM Costs 
GROUP BY month(date_field)

SELECT month(date_field), SUM(cost_field)
FROM Sales
GROUP BY month(date_field)

This is for each month.

Do you need the same list with totals for each year?

In that case it would be almost the same query

SELECT year(date_field), SUM(cost_field)
FROM Costs 
GROUP BY year(date_field)

SELECT year(date_field), SUM(cost_field)
FROM Sales
GROUP BY year(date_field)
hgulyan
Perfecto! thankyou.
Jacob
You're welcome.
hgulyan
Just one more question, how would I show just one particular month? For example to show all the purchases for the set months, january, febuary, without having to explicitly defined the date ranges?
Jacob
Or, just for the moment to make it easier, how would you do the current month regardless of what month it is?
Jacob
Actually, I think I need to make another question on dealing with the data in PHP, or should I edit this question?
Jacob
you can add WHERE clause to your query. You shoud add "WHERE month(date_field) = 6" for June, 7 for July etc. If you want to get current month it would be "WHERE month(date_field) = month(getdate())"
hgulyan
ahh, awesome :)
Jacob
It seems that you don't know about upvote/downvote system? Please, read faq. If answer is usefull you should upvote it.
hgulyan
Jacob, p.s. I think you should read some tutorials or a book on how to work with sql in php.
hgulyan
sorry, I did not realize I could vote. I have upvoted you. I actually have a quetsion, as it seems I was not thinking before. Your query only returns two columns, month(saledate) and SUM(cost). Per my questions though, I want to show purchases costs separate from sales costs. Should this still be two seperate queries?
Jacob