Skip to content
Advertisement

MySQL query get total of payments for everyday of the month until current date

I’m trying to build a MySQL query to get the total amount for every day of the month until the current date. I’m not sure if it’s possible with just one query. It would be something like:

Today’s date = ‘2021-02-24’

Select 
    SUM(CASE WHEN transactionDate = '2020-02-01' THEN amount ELSE 0 END) AS Total01,
    SUM(CASE WHEN transactionDate = '2020-02-02' THEN amount ELSE 0 END) AS Total03,
    SUM(CASE WHEN transactionDate = '2020-02-03' THEN amount ELSE 0 END) AS Total03,
    ...
    SUM(CASE WHEN transactionDate = '2020-02-24' THEN amount ELSE 0 END) AS Total24
From myTable

In the end, I would have the total amount for every day. Does it make sense?

Thanks

Advertisement

Answer

I would rather use something like this:

SELECT
   sum(`amount`) as `amount`, DATE(`transactionDate`) as `date`
FROM
   `myTable`
GROUP BY
   DATE(`transactionDate`)
;

This will return rows for each date in database (casted to be only date without time part)

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