如果缺少,Oracle 添加顺序查询行

Oracle add sequential query rows if missing

在 Oracle 19c 中我有这样的数据:

with t as (
select 1 Cat, 1 id, 11 val from dual
 union all
select 1, 3, 33 from dual
 union all
select 2, 2, 22 from dual
 union all
select 2, 4, 44 from dual)
select * 
  from t

在查询结果中,我希望每个 cat 获得 4 行,id 为 1-4,如果 id 中没有这样的 cat val 必须为空:

cat id val
1 1 11
1 2
1 3 33
1 4
2 1
2 2 22
2 3
2 4 44

使用 PARTITIONed 连接与 row-generator:

SELECT t.cat,
       i.id,
       t.val
FROM   (SELECT LEVEL AS id FROM DUAL CONNECT BY LEVEL <= 4) i
       LEFT OUTER JOIN t
       PARTITION BY (t.cat)
       ON (i.id = t.id)

输出:

CAT ID VAL
1 1 11
1 2 null
1 3 33
1 4 null
2 1 null
2 2 22
2 3 null
2 4 44

db<>fiddle here