SQL 追加记录

SQL to append records

我有两个表 tbl1 和 tbl2。将 tbl2 视为主要集,tbl1 是从其他来源派生的,但现在基本上是 tbl2 的子集。

tbl1

cd productcd type
1 1 A
1 2 AB
1 3 A
2 3 AB
2 4 AC
3 1 A

tbl2

cd productcd type priority
1 1 A 1
1 2 AB 2
1 3 A 3
1 4 AB 4
1 5 AC 7
2 1 A 3
2 3 AB 4
2 4 AC 8
2 7 HV 10
3 1 A 2
3 2 AC 3
3 7 BC 5
3 4 E 9
3 5 T 11

如何为每组 CD 检索限制每组只有 4 条记录? 所以最后的 o/p 必须是 tbl1 的所有记录,缺失的记录(最大限制为 4)将从 tbl2

填充

最终o/p被

cd productcd type
1 1 A
1 2 AB
1 3 A
1 4 AB
2 3 AB
2 4 AC
2 1 A
2 7 HV
3 1 A
3 2 AC
3 7 BC
3 4 E

如果我理解正确,您可以使用 row_number 到 select 并为每个 cd 排序所需的行,并使用 exists 优先排序来自 [=14= 的行]

with t as (
  select *, 
    Row_Number() over(
        partition by cd 
        order by 
            case when exists (
                    select * from tbl1 where tbl1.cd=tbl2.cd and tbl1.productcd=tbl2.productcd
                ) then 0 else 1 
            end, priority) rn
  from tbl2
)
select cd, productcd, type
from t
where rn<=4

Working DB<>Fiddle