Answer the question
In order to leave comments, you need to log in
MySQL COUNT, SUM with GROUP BY showing nonexistent values?
There is a table `table` of calls with user, datetime, duration, call_id
fields. Data is duplicated in user, datetime fields.
I get the total number of calls and their duration for the period as follows:
SELECT `user`, DATE(`datetime`) as `date`, count(`duration`) as `count`
FROM `table`
WHERE
`datetime` >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
GROUP BY `date` DESC, `user` ASC
Answer the question
In order to leave comments, you need to log in
Fill in user variables min. and max. datetime field value:
SELECT MIN(`datetime`), MAX(`datetime`)
FROM `table`
WHERE TIMESTAMP BETWEEN "2014-10-01" AND "2017-10-31"
INTO @min_d, @max_d;
SET @n:=date(@max_d + INTERVAL 1 DAY);
SELECT * FROM
/* Все пользователи */
(SELECT DISTINCT `user`
FROM `table`
WHERE
NOT ISNULL(`user`)
) AS `users`
RIGHT OUTER JOIN
/* Все даты запрошенных дней */
(SELECT (SELECT @n:= @n - INTERVAL 1 DAY) AS `date`
FROM `table`
WHERE @n >= DATE_SUB(@max_d, INTERVAL DATEDIFF(@max_d,@min_d) DAY) AND
NOT ISNULL(`user`)
) AS `datetime`
ON TRUE
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question