[英]Value for missing data in SQL
SELECT * FROM MyDB WHERE Meter = 'MeterX' AND Date > '1-AUG-2022' AND Date <= '5-AUG-2022' ORDER BY Date;
I would query much larger date ranges so would usually miss if there is a date missing.我会查询更大的日期范围,因此如果缺少日期,通常会错过。 Is there a way that I can have a value returned in the Quality column like "Missing" if that partiqular day is missing from the database?
如果数据库中缺少特定日期,是否可以在“质量”列中返回一个值,例如“缺少”? This means that I also need the missing date in the Date column.
这意味着我还需要 Date 列中缺少的日期。 I also only have read access, so no creating temp tables to join with.
我也只有读取权限,所以没有创建临时表来加入。
Thank you.谢谢你。
Use a PARTITION
ed OUTER JOIN
to a row-generator:对行生成器使用
PARTITION
ed OUTER JOIN
:
SELECT c.day,
m.meter,
COALESCE(m.quality, 0) AS quality
FROM (
SELECT DATE '2022-08-01' + (LEVEL - 1) AS day
FROM DUAL
CONNECT BY DATE '2022-08-01' + (LEVEL - 1) <= DATE '2022-08-05'
) c
LEFT OUTER JOIN MyDB m
PARTITION BY (m.meter)
ON (c.day <= m."DATE" and m."DATE" < c.day + 1)
WHERE m.Meter = 'MeterX'
ORDER BY c.day;
Which, for the sample data:其中,对于样本数据:
CREATE TABLE mydb ("DATE", meter, quality) AS
SELECT DATE '2022-08-01', 'MeterX', 42 FROM DUAL UNION ALL
SELECT DATE '2022-08-02', 'MeterX', 23 FROM DUAL UNION ALL
SELECT DATE '2022-08-04', 'MeterX', 7 FROM DUAL UNION ALL
SELECT DATE '2022-08-05', 'MeterX', 99 FROM DUAL;
Outputs:输出:
DAY 天
METER 仪表
QUALITY 质量
01-AUG-22 01-AUG-22
MeterX MeterX
42 42
02-AUG-22 02-AUG-22
MeterX MeterX
23 23
03-AUG-22 22 年 8 月 3 日
MeterX MeterX
0 0
04-AUG-22 22 年 8 月 4 日
MeterX MeterX
7 7
05-AUG-22 22 年 8 月 5 日
MeterX MeterX
99 99
for postgres this could work for you对于postgres,这可能对你有用
with date_dimension as (
SELECT dd::DATE
FROM generate_series
( '2022-08-01'::timestamp
, '2022-08-05'::timestamp
, '1 day'::interval) dd
)
select *
from my_table
left join date_dimension on date_dimension.dd = my_table.Date
where Meter = 'MeterX'
and Date > '2022-08-01'
and Date <= '2022-08-05'
order by Date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.