Answer the question
In order to leave comments, you need to log in
How to collect statistics for different periods of time?
I have a database in which I store information about the replenishment and the date of replenishment. I know how to calculate replenishment for 24 hours. And how to calculate at once for 24, a week and a month? One request.
SELECT `id_user`, SUM(`sum`) `sum`, users.name FROM `balance_history` INNER JOIN `users` ON `id_user` = users.id WHERE `date` >= NOW() - INTERVAL 1 DAY AND `type` = 'plus' GROUP BY `id_user` ORDER BY `sum` DESC
Answer the question
In order to leave comments, you need to log in
Use conditional aggregation.
SELECT `id_user`,
SUM(`sum`) `sum_month`,
SUM(`sum` * (`date` >= NOW() - INTERVAL 1 WEEK)) `sum_week`,
SUM(`sum` * (`date` >= NOW() - INTERVAL 1 DAY)) `sum_day`,
users.name
FROM `balance_history`
INNER JOIN `users` ON `id_user` = users.id
WHERE `date` >= NOW() - INTERVAL 1 MONTH
AND `type` = 'plus'
GROUP BY `id_user`, users.name
ORDER BY `sum` DESC
SUM(CASE WHEN {some condition}
THEN {some value}
ELSE 0
END)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question