MYSQL select 具有预定义值的数据,如果日期不存在于同一 table
MYSQL select data with predefined values if date not exist in same table
我的结果 sql 语法为:
SELECT AreaName, Date, Total
FROM table
GROUP BY AreaName, Date
此处结果:
AreaName
Date
Total
London
2021-01-01
2
Paris
2021-01-01
3
London
2021-02-01
4
Beijing
2021-02-01
5
但如果日期数据不存在且总计值为 0,我想包括 AreaName。像这里一样:
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
有什么建议吗?
WITH
areas AS ( SELECT DISTINCT AreaName
FROM source_table ),
dates AS ( SELECT DISTINCT `Date`
FROM source_table )
SELECT AreaName, `Date`, COALESCE(Total, 0) Total
FROM areas
CROSS JOIN dates
NATURAL LEFT JOIN source_table;
我们可以使用 sub-queries 和 DISTINCT 来获取所有日期和所有 AreaNames 的列表,然后交叉连接它们。
警告:这会使值相乘,并可能快速创建一个包含大量零值的巨大结果集。
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
我的结果 sql 语法为:
SELECT AreaName, Date, Total
FROM table
GROUP BY AreaName, Date
此处结果:
AreaName | Date | Total |
---|---|---|
London | 2021-01-01 | 2 |
Paris | 2021-01-01 | 3 |
London | 2021-02-01 | 4 |
Beijing | 2021-02-01 | 5 |
但如果日期数据不存在且总计值为 0,我想包括 AreaName。像这里一样:
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 |
有什么建议吗?
WITH
areas AS ( SELECT DISTINCT AreaName
FROM source_table ),
dates AS ( SELECT DISTINCT `Date`
FROM source_table )
SELECT AreaName, `Date`, COALESCE(Total, 0) Total
FROM areas
CROSS JOIN dates
NATURAL LEFT JOIN source_table;
我们可以使用 sub-queries 和 DISTINCT 来获取所有日期和所有 AreaNames 的列表,然后交叉连接它们。
警告:这会使值相乘,并可能快速创建一个包含大量零值的巨大结果集。
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