问题
I´m trying to fill the gaps after using group by using an aux table, can you help?
aux table to deal with days with no orders
date quantity
2014-01-01 0
2014-01-02 0
2014-01-03 0
2014-01-04 0
2014-01-05 0
2014-01-06 0
2014-01-07 0
group by result from "orders" table
date quantity
2014-01-01 7
2014-01-02 1
2014-01-04 2
2014-01-05 3
desired result joining "orders" table with "aux table"
date quantity
2014-01-01 7
2014-01-02 1
2014-01-03 0
2014-01-04 2
2014-01-05 3
2014-01-06 0
2014-01-07 0
回答1:
Without knowing how you create your group by result
table, what you're looking for in an outer join
, perhaps with coalesce
. Something like this:
select distinct a.date, coalesce(b.quantity,0) quantity
from aux a
left join yourgroupbyresults b on a.date = b.date
Please note, you may or may not need distinct
-- depends on your data.
Edit, given your comments, this should work:
select a.date, count(b.date_sent)
from aux a
left join orders b on a.date = date_format(b.date_sent, '%Y-%m-%d')
group by a.date
- SQL Fiddle Demo
回答2:
Using your results it would be something like:
SELECT a.date
,COALESCE(b.quantity,0) as quantity
FROM auxtable a
LEFT JOIN groupbyresult b
ON a.date = b.date
You can also do your grouping in the same query as the left join:
SELECT a.date
,COALESCE(COUNT(b.somefield),0) as quantity
FROM auxtable a
LEFT JOIN table1 b
ON a.date = b.date
GROUP BY a.date
回答3:
One familiar approach to solving a problem like this is to use a row source that has the distinct list of dates you want to return, and then do an outer join to the table that has gaps. That way, you get all the dates back, and you can substitute a zero for the "missing" quantity values.
For example:
SELECT d.date
, IFNULL(SUM(s.quantity),0) AS quantity
FROM distinct_list_of_dates d
LEFT
JOIN information_source s
ON s.date = d.date
GROUP BY d.date
It's not clear why a GROUP BY would be eliminating some date values. We might conjecture that you are using a MySQL extension to ANSI-standard GROUP BY semantics, and that is eliminating rows. Or, you may have a WHERE clause that is excluding rows. But we're just guessing.
FOLLOW UP based on further information revealed by OP in comments...
In the query above, replace distinct_list_of_dates
with aux
, and replace information_source
with orders
, and adjusting the join predicate to account for datetime comparison to date
SELECT d.date
, IFNULL(SUM(s.quantity),0) AS quantity
FROM aux d
LEFT
JOIN orders s
ON s.date >= d.date
AND s.date < d.date + INTERVAL 1 DAY
GROUP BY d.date
来源:https://stackoverflow.com/questions/27695996/mysql-fill-group-by-gaps