Get totals by date range, relating to additional table [closed]

1

The case is as follows, I have a table in MySQL for a company box, and I'm creating a table in JAVA that will be a cost center. The database table has the columns:

id | data | descricao | id_tipoDespesa | valor |

I need the total amount of each expense in a specific range of dates and also relate id_tipoDespesa to the type of expense it represents.

The result I need is as in the example:

periodo:
de: data1 até: data2

despesa  | valor |
__________________
agua     | 1000  |
luz      | 2004  |
telefone | 503   |

I still do not know almost anything about MySQL and no other database language, please try to explain as simple as possible kkkk

    
asked by anonymous 22.08.2016 / 01:29

1 answer

2

You have several problems in one issue.

Grouping and Summing

One of them is the problem of grouping and totalizing. You have multiple releases for id_tipos different, but you want to show one per line with your 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 Date Range

As you want a specific range, we need to limit the query above with a condition ( WHERE ). We could say WHERE data >= data_inicial AND data <= data_final , but to make it easier, there is an operator for this, BETWEEN :

SELECT   SUM(valor)
FROM     despesas
WHERE    'data' BETWEEN "2016-04-01" AND "2016-07-30"
GROUP BY id_tipos
;


Relating to another table

The query above already gives the totals, but lacked the type of expense in question. For this, we use 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 working and testing the SQL Fiddle ;


General considerations

  • Important : The correct for fields with date and time is the following format:

    WHERE 'data' BETWEEN "2016-04-01 00:00:00" AND "2016-07-30 23:59:59"
    

    Note the 23:59:59 at the end date time, which is to catch events occurring all day long. If you omit the time, the results.

  • The GROUP BY separates the results of SUM (or any other grouping functions) into separate rows according to the selected fields

  • The AS total no SUM serves to give a friendly nickname for the column, which will return with the name of total , to facilitate use in the application

  • We use prefix in tipos.id in ON for disambiguation, since the id field exists in both tables. We are making it clear that this is id of table tipos


Learn more about JOIN in

  

What's the difference between INNER JOIN and OUTER JOIN?

    
22.08.2016 / 02:25