17,086
社区成员
发帖
与我相关
我的任务
分享
select case when c.id2 is null then c.id1 else null end id,
case when c.id2 is null then c.money1 else null end money,
c.money from
(
select a.id id1,lag(a.id) over(partition by a.id order by a.id) id2,
a.money MONEY1,
b.money money
from a left join b on a.id=b.id
) c
with a as(
select 'A' as id,5 as money from dual
union all
select 'B' as id,7 as money from dual
union all
select 'C' as id,10 as money from dual
),
B AS (
select 'A' as id,2 as money from dual
union all
select 'A' as id,3 as money from dual
union all
select 'B' as id,1 as money from dual
union all
select 'B' as id,2 as money from dual
union all
select 'B' as id,4 as money from dual
union all
select 'C' as id,2 as money from dual
union all
select 'C' as id,3 as money from dual
union all
select 'C' as id,1 as money from dual
union all
select 'C' as id,1 as money from dual
)
SELECT DECODE(C.R, 1, A.ID) ID, DECODE(C.R, 1, A.MONEY) "金额", C.MONEY "分配金额"
FROM A
LEFT JOIN (SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ROWNUM) AS R,
ID, MONEY
FROM B) C
ON C.ID = A.ID
with a as(
select 'A' as id,5 as money from dual
union all
select 'B' as id,7 as money from dual
union all
select 'C' as id,10 as money from dual
),
B AS (
select 'A' as id,2 as money from dual
union all
select 'A' as id,3 as money from dual
union all
select 'B' as id,1 as money from dual
union all
select 'B' as id,2 as money from dual
union all
select 'B' as id,4 as money from dual
union all
select 'C' as id,2 as money from dual
union all
select 'C' as id,3 as money from dual
union all
select 'C' as id,1 as money from dual
)
select case when c.id2 is null then c.id1 else null end id,
case when c.money2 is null then c.money1 else null end money,
c.money from
(select a.id id1,lag(a.id) over(partition by a.id order by a.id nulls last) id2,
a.money money1,lag(a.money) over(partition by a.money order by a.money nulls last) money2,
b.money money
from a left join b on a.id=b.id) c
能实现结果,但不是最优的……