Skip to content
Advertisement

How sum values in days intervals MySQL 5.7?

I have a server with MySQL 5.7. I have two tables. First one t contains creating dates for each id. Second table t0 contains profit records day by day for each id. I want to get columns with sums of profit for first and second 30 days for each id as well as for the first day.

This code runs but sums are wrong because sum of the first day much more then monthly. Where I’m wrong and how to fix it?

Advertisement

Answer

Your problem statement is not that clear, but based on your attempt, I suspect that you can do conditional aggregation:

The logic is to join just once, and then to use case expressions within the sum()s to choose which values should be taken into account.

I changed the date filtering logic to use half-open intervals rather than between, because it seems more relevant to me. You can adapt that as you wish according to your actual use case.

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