Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MYSQL select data with predefined values if date not exist in same table

I have resutl sql with syntax:

SELECT AreaName, Date, Total
FROM table
GROUP BY AreaName, Date

Here Result:

AreaName Date Total
London 2021-01-01 2
Paris 2021-01-01 3
London 2021-02-01 4
Beijing 2021-02-01 5

But I want include AreaName if date data not exist with value Total 0. Like here:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

AreaName Date Total
London 2021-01-01 2
Paris 2021-01-01 3
Beijing 2021-01-01 0
London 2021-02-01 4
Paris 2021-02-01 0
Beijing 2021-02-01 5

Any Advice ?

>Solution :

We can use sub-queries with DISTINCT to get lists of all dates and all AreaNames and then cross join them.
Warning: this multiplies the values and could quickly create an enormous result set containing a host of zero values.

create table Areas(
AreaName varchar(25),
AreaDate Date,
Total int);
insert into Areas values
('London', '2021-01-01',  2),
('Paris',  '2021-01-01',  3),
('London', '2021-02-01',  4),
('Beijing','2021-02-01',  5);
select
  a.AreaName,
  b.AreaDate,
  coalesce(c.Total,0) "Total"
from
(select distinct AreaName from Areas) a
cross join 
(select distinct AreaDate from Areas) b
left join Areas c
on a.AreaName = c.AreaName
and b.AreaDate = c.AreaDate
order by AreaDate, AreaName
AreaName | AreaDate   | Total
:------- | :--------- | ----:
Beijing  | 2021-01-01 |     0
London   | 2021-01-01 |     2
Paris    | 2021-01-01 |     3
Beijing  | 2021-02-01 |     5
London   | 2021-02-01 |     4
Paris    | 2021-02-01 |     0

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading