M
M
maks789452019-12-12 23:29:45
SQL
maks78945, 2019-12-12 23:29:45

How to merge two tables by date?

Hello, there are 2 tables
time_dimension
id
db_date
client
id
date_create
delete
name
......
I want to get the number of records from the clients table for each day, there can be several or 0. The time_dimension table stores all dates for 10 years.
I managed to get this list with the following query:

SELECT 
  time_dimension.db_date, COUNT(clients.date_create)
FROM
  time_dimension
LEFT JOIN 
  clients
ON
  time_dimension.db_date = DATE_FORMAT(clients.date_create,"%Y-%m-%d")
WHERE 
  time_dimension.db_date BETWEEN '2019-12-01' AND '2019-12-30'
GROUP BY
  time_dimension.db_date
ORDER BY
  time_dimension.db_date

but if I add clients.`delete`='0' in while I get records only for the days when there were new clients, and all days for the period are necessary

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
d-stream, 2019-12-13
@d-stream

Direct variant - full join
Only whether it is necessary to receive a cloth from ~3650 lines where quantities different from zero will occasionally flicker here and there?
ps judging by the structure of time_dimension - it was done approximately for this
pps I strongly suspect that all this should then fall into some graphs of the dynamics of the client base, it is better to feed raw data there

K
Konstantin Tsvetkov, 2019-12-13
@tsklab

If d-stream is right and you need a calendar report, for example:
Then the following variant of its construction is suggested: q628559 .

K
kodv, 2019-12-13
@kodv

As I understand it, when you wrote while. you meant WHERE. Then you need to move the clients.`delete`='0' clause from the WHERE clause to the ON clause.

SELECT 
  time_dimension.db_date, COUNT(clients.date_create)
FROM
  time_dimension
LEFT JOIN 
  clients
ON
  time_dimension.db_date = DATE_FORMAT(clients.date_create,"%Y-%m-%d")
  AND clients.`delete`='0'
WHERE 
  time_dimension.db_date BETWEEN '2019-12-01' AND '2019-12-30'
GROUP BY
  time_dimension.db_date
ORDER BY
  time_dimension.db_date

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question