Oracle查询连续年,月,日的数据
报表开发有时候需要查询连续时间的数据,但是如果中间有一些时间没有数据,就会导致查询出来的时间不连续。
例如:
-- 年, 品牌,销售额
create table SALES_INFO
(
year NUMBER(4),
brand VARCHAR2(30),
sales NUMBER
)
insert into SALES_INFO values (2022, 'x', 100);
insert into SALES_INFO values (2018, 'x', 100);
insert into SALES_INFO values (2019, 'x', 100);
insert into SALES_INFO values (2021, 'x', 100);
commit;
需要查询x品牌连续5年(2018-2022)的数据,但是没有2020年的数据,正常单表查询就会导致查询出来的结果中间少了2020年的那一行。
解决方法
使用left join,将连续的时间left join业务表,查询x连续5年的结果
select a.year, 'x' as brand, b.sales
from (select (2022 - rownum + 1) as year from dual connect by rownum < 6) a
left join (select * from SALES_INFO) b
on a.year = b.year
order by a.year

连续几月和几天的数据,如果没有数据的显示为空也是同理
月
连续几月SQL
select to_char(add_months(to_date('202201', 'YYYYMM'), rownum), 'yyyymm') as month
from dual
connect by rownum < 6
一周连续七天
一周连续7天SQL
select to_char(sysdate - to_number(to_char(sysdate, 'D')) + level+1, 'YYYY-MM-DD') day
from dual
connect by level <= 7
版权声明:本文为sunday2018原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。