我有一个表,其中包含一些列,其中一个列包含月份。我为字段FILTERXML
保留了至少1个月的行,并且我希望为错过的月份带来数据,而其他列的值则完全相同,但总和中我想将其置零。
我想重写SQL以消除行之间的间隙,并同时显示缺少月份信息的行。
这是我的SQL,仅对一个U_VATX
有效:
U_VATX
答案 0 :(得分:1)
您可以使用LEFT OUTER JOIN。以下基于您的示例。 “ bla”部分可能需要修改以适合您的需求。希望这会有所帮助。
create table demo (
cola varchar2(10),
colb varchar2(10),
colc varchar2(10),
colmonth varchar2(2),
colsum1 number,
colsum2 number
);
insert into demo values ('bla','bla','bla','01',35,48);
insert into demo values ('bla','bla','bla','03',22,41);
select * from demo;
select
nvl(demo.cola, 'bla'),
nvl(demo.colb, 'bla'),
nvl(demo.colc, 'bla'),
nvl(demo.colmonth, a.colmonth),
nvl(demo.colsum1, 0),
nvl(demo.colsum2, 0)
from (select '01' as colmonth from dual
union
select '02' as colmonth from dual
union
select '03' as colmonth from dual) a
left outer join demo on a.colmonth = demo.colmonth
order by 1;
根据表的大小,“ bla”部分的处理方式如下。
with bla as
(select distinct
cola, colb, colc,
'00' as colmonth,
0 as colsum1,
0 as colsum2
from demo
group by cola, colb, colc),
mth as
(select '01' as colmonth from dual
union
select '02' as colmonth from dual
union
select '03' as colmonth from dual),
blamth as
(select bla.cola, bla.colb, bla.colc,
mth.colmonth, bla.colsum1, bla.colsum2
from bla, mth)
select
nvl(demo.cola, blamth.cola),
nvl(demo.colb, blamth.colb),
nvl(demo.colc, blamth.colc),
nvl(demo.colmonth, blamth.colmonth),
nvl(demo.colsum1, 0),
nvl(demo.colsum2, 0)
from demo right outer join blamth
on demo.colmonth = blamth.colmonth
order by 1;
您可以在此处进行检查:http://sqlfiddle.com/#!4/1d267a/31
基于“ colx”和“ sumcolsum”要求的新解决方案。
with bla as
(select distinct colx, cola, colb, colc
from demo),
mth as
(select '01' as colmonth from dual
union
select '02' as colmonth from dual
union
select '03' as colmonth from dual
union
select '04' as colmonth from dual
union
select '05' as colmonth from dual),
blamth as
(select bla.colx, bla.cola, bla.colb, bla.colc,
mth.colmonth
from bla, mth),
allcols as
(select
nvl(demo.colx, blamth.colx) as colx,
nvl(demo.cola, blamth.cola) as cola,
nvl(demo.colb, blamth.colb) as colb,
nvl(demo.colc, blamth.colc) as colc,
nvl(demo.colmonth, blamth.colmonth) as colmonth,
nvl(demo.colsum1, 0) as colsum1,
nvl(demo.colsum2, 0) as colsum2
from demo right outer join blamth
on demo.colx = blamth.colx and
demo.colmonth = blamth.colmonth)
select allcols.colx,
allcols.cola,
allcols.colb,
allcols.colc,
allcols.colmonth,
allcols.colsum1,
allcols.colsum2,
(select sum(nvl(ai.colsum1,0))
from allcols ai
where ai.colx = allcols.colx
and ai.cola = allcols.cola
and ai.colb = allcols.colb
and ai.colc = allcols.colc) as sumcolsum1,
(select sum(nvl(ai.colsum2,0))
from allcols ai
where ai.colx = allcols.colx
and ai.cola = allcols.cola
and ai.colb = allcols.colb
and ai.colc = allcols.colc) as sumcolsum2
from allcols
order by 1, 5;
为此提供了新的SQL提琴:http://sqlfiddle.com/#!4/75813f/16
答案 1 :(得分:0)
Oracle SQL允许使用“分区外部联接”填充稀疏数据。
此处https://docs.oracle.com/cd/E11882_01/server.112/e25555/tdpdw_sql.htm#TDPDW0072记录了11.2,但由于其复杂性,我不会尝试在您的特定代码上实现它。