我有一个记录赛季得分的表格,下面是score_table。它记录了一个主题三季的得分S1,S2和S3.
有时,人们可以放弃一些季节的分数和化妆后,通过获得另一个主题相同的季节评分,所以我们有transfe_record表保存它。
因此,问题是如何使用SQL( transfe_record )代码使用DB2将分数写回来。
谢谢!
score_table
| key | subject | S1 | S2 | S3 |
+--------------+---------------+-----------+-----------+-----------|
| 1 | A01 | 80 | 80 | 100 |
| 1 | A02 | 78 | 98 | null |
| 1 | A03 | null | 80 | null |
| 1 | B01 | null | null | null |
| 1 | B02 | null | null | 60 |
| 1 | B03 | 66 | null | null |transfe_record
| key | org_sbj | trans_sbj |
+---------------+---------------+----------------+
| 1 | A02 | B02 |
| 1 | A03 | B03 |在SQL之后,score_table应该是
| key | subject | S1 | S2 | S3 |
+--------------+---------------+-----------+-----------+-----------|
| 1 | A01 | 80 | 80 | 100 |
| 1 | A02 | 78 | 98 | 60 |
| 1 | A03 | 66 | 80 | null |
| 1 | B01 | null | null | null |
| 1 | B02 | null | null | 60 |
| 1 | B03 | 66 | null | null |发布于 2019-09-02 10:56:55
试试这个:
merge into score_table a using
(
select t.key, t.org_sbj, b.S1, b.S2, b.S3
from transfe_record t
join score_table b on b.key=t.key and b.subject=t.trans_sbj
) m on m.key=a.key and m.org_sbj=a.subject
and (a.S1 is null or a.S2 is null or a.S3 is null)
when matched then update set
S1=coalesce(a.S1, m.S1)
, S2=coalesce(a.S2, m.S2)
, S3=coalesce(a.S3, m.S3);选择要插入到新表中的语句:
select
a.key, a.subject
, coalesce(a.S1, b.S1) as S1
, coalesce(a.S2, b.S2) as S2
, coalesce(a.S3, b.S3) as S3
from score_table a
left join transfe_record t on t.key=a.key and t.org_sbj=a.subject
left join score_table b on b.key=t.key and b.subject=t.trans_sbj;https://stackoverflow.com/questions/57754334
复制相似问题