我有一张桌子
ID ID2 VARIABLE VA_VAL
1 100 F_NAME ABC
1 102 QUAL 01
1 103 CODE 1923
2 100 F_NAME BCD
2 102 QUAL 02
2 103 CODE 2034
3 100 F_NAME CDE
3 102 QUAL 01
3 103 CODE 5436
如果ID2 = 102并且VARIABLE = QUAL且VA_VAL = 01,则插入 ID2 = 104,VARIABLE = NEW_CD1和VA_VAL =((ID2 = 103和VARIABLE = CODE)的VA_VAL)
此外,删除同一ID的行(ID2 = 102且VARIABLE = QUAL和VA_VAL = 02)和(ID2 = 103且VARIABLE = CODE)。
如果ID2 = 102并且VARIABLE = QUAL和VA_VAL = 02,则插入 ID2 = 103,VARIABLE = NEW_CD2和VA_VAL =((ID2 = 103和VARIABLE = CODE)的VA_VAL)
此外,删除同一ID的行(ID2 = 102且VARIABLE = QUAL和VA_VAL = 02)和(ID2 = 103且VARIABLE = CODE)。
输出表如下:
ID ID2 VARIABLE VA_VAL
1 100 F_NAME ABC
1 104 NEW_CD1 1923
2 100 F_NAME BCD
2 105 NEW_CD2 2034
3 100 F_NAME CDE
3 104 NEW_CD1 5436
在Oracle SQL中有没有一种有效的方法?我桌上有超过5000万条记录。
答案 0 :(得分:1)
我假设您只想要一个结果集。这是想法:
结果查询如下:
select ID, ID2, VARIABLE, VA_VAL
from t
where not ((ID2 = 102 and VARIABLE = 'QUAL' and VA_VAL = '02') or
(ID2 = 103 and VARIABLE = 'CODE')
)
union all
select t.id, 104 as id2, 'NEW_CD1',
max(case when ID2 = 103 and VARIABLE = 'CODE' then VA_VAL end)
from t
group by t.id
having max(case when ID2 = 103 and VARIABLE = 'CODE' then VA_VAL end) is not null
union all
select t.id, 104 as id2, 'NEW_CD1',
max(case when ID2 = 102 and VARIABLE = 'QUAL' then VA_VAL end
from t
group by t.id
having max(case when ID2 = 102 and VARIABLE = 'QUAL' then VA_VAL end) is not null;
如果要替换现有表-并且有很多更改(我认为是正确的)-运行此查询并将结果保存在表中。
然后,截断现有表并将值重新插入其中。