Skip to content
Advertisement

SELECT a query after another SELECT using Dates

i have a table that uses TIMESTAMPS an needs to be filtered by month, the query is:

SELECT * FROM  tx_gas 
WHERE TO_CHAR(date_prod, 'YYYYMM') = '202103';

now, from the results of this query i need to use another query that groups the dates by day and makes a sum of a field, in the same table:

SELECT SUM(liters) AS LITERS,
        TO_CHAR( TRUNC(date_prod), 'DD/MM/YYYY') AS GROUPED_DATE
FROM tx_gas
GROUP   BY   TRUNC(date_prod)
ORDER   BY   TRUNC(date_prod) ASC;

How can i join this two querys so the two separated queries can be made in just one?

Advertisement

Answer

SELECT SUM(liters) AS LITERS,
        TO_CHAR(TRUNC(date_prod), 'DD/MM/YYYY') AS GROUPED_DATE
FROM tx_gas
WHERE TO_CHAR(date_prod, 'YYYYMM') = '202103'
GROUP   BY   TRUNC(date_prod)
ORDER   BY   TRUNC(date_prod) ASC;

That should do the trick; you don’t need a second query as you want to filter the table down to a set of rows and then you want to output and aggregate those results

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement