You have a lot of problems in one question.
Grouping and summing
One of them is the problem of grouping and totalization. You have several releases for id_tipos
different but wants to show one per line with their totals.
The solution to this is to group with GROUP BY
, and get the value with SUM
:
SELECT SUM(valor)
FROM despesas
GROUP BY id_tipos;
Selecting range of dates
Since you want a specific interval, we need to limit the query above with one condition (WHERE
). We could say WHERE data >= data_inicial AND data <= data_final
, but to facilitate, there is an operator for this, the BETWEEN
:
SELECT SUM(valor)
FROM despesas
WHERE `data` BETWEEN "2016-04-01" AND "2016-07-30"
GROUP BY id_tipos
;
Relating to the other table
To query above already gives the totals, but lacked the type of expense in question. For this, we use the JOIN
, conditioned with ON
:
SELECT tipo,
SUM(valor) AS total
FROM despesas
LEFT JOIN tipos ON tipos.id = id_tipos
WHERE `data` BETWEEN "2016-04-01" AND "2016-07-30"
GROUP BY id_tipos
;
See it working and do more tests on SQL Fiddle;
General considerations
Important: The correct for fields with date and time is the format below:
WHERE `data` BETWEEN "2016-04-01 00:00:00" AND "2016-07-30 23:59:59"
note the 23:59:59
at the time of the final date, which is to pick up events that have occurred all day. If omit the time, the results.
The GROUP BY
separates the results from the SUM
(or any other grouping functions) on separate lines according to the selected fields
The AS total
in the SUM
serves to give a friendly nickname to the column, which will return with the name of total
, to facilitate use in the application
We use prefix on tipos.id
in the ON
for disambiguation, because the field id
exists in both tables. We are making it clear that this is the id
table tipos
Learn more about JOIN
in
What is the difference between INNER JOIN and OUTER JOIN?
When you say "[...]I’m creating a table in JAVA[...]" it’s kind of like
gridview
just to display the data? Or store something too?– Marcelo de Andrade
Here are some examples of JOIN: http://answall.com/questions/6441/70. Join is used to list tables by certain conditions and/or columns. But if you don’t know much about comics yet, I would suggest starting with something simpler, and asking specific questions about every step you have difficulty with. Stack Overflow in Portuguese is a Q and A site, not a forum with tutorials. There are some tips that can help you better enjoy the site on [Tour], Topics appropriate to the site, [Ask]. Solving doubts step by step is the best way.
– Bacco
A simple way to test SQL and Joins is to read the link above, and apply to SQL Fiddle, so you can share your tests and the community can help. Creating a [mcve] with sample data, in the format you want the results facilitates for everyone.
– Bacco