OracleSQL:如果值为空,则检索邻接字段的值
我得到了一个大表a,如果当前字段(文本)为空,则需要获取组(列:Key)中填充的相邻字段(代码:K_p_1)的值。组不一定有代码为K_P_1的字段。我的查询中有很多连接,希望下面的示例能使我的问题更接近 我的想法:我实际上认为我可以通过右外连接解决我的问题,但我不知道该组合什么键。当我检查case语句时,我丢失了对相邻字段的引用 我的表A:OracleSQL:如果值为空,则检索邻接字段的值,sql,oracle,Sql,Oracle,我得到了一个大表a,如果当前字段(文本)为空,则需要获取组(列:Key)中填充的相邻字段(代码:K_p_1)的值。组不一定有代码为K_P_1的字段。我的查询中有很多连接,希望下面的示例能使我的问题更接近 我的想法:我实际上认为我可以通过右外连接解决我的问题,但我不知道该组合什么键。当我检查case语句时,我丢失了对相邻字段的引用 我的表A: select Key, Code, Text from A; Key Code Text 11K K_P_1 text 11K K_P_2 (n
select Key, Code, Text from A;
Key Code Text
11K K_P_1 text
11K K_P_2 (null)
11K K_P_3 (null)
12K K_P_1 text2
12K K_P_2 (null)
12K K_P_3 (null)
我的想法是:
Key Code Text FamilyText
11K K_P_1 text text
11K K_P_2 (null) text
11K K_P_3 (null) text
12K K_P_1 text2 text2
12K K_P_2 (null) text2
12K K_P_3 (null) text2
您可以使用窗口功能:
哇,很好用。我没想到解决这个问题会这么舒服,谢谢@马维德耶斯很高兴我能帮上忙。SQL是一种强大的编程语言:)“忽略空值”在这种情况下不是必需的。我不完全理解这个问题。如果多个键都有值,而其他键都是空的怎么办?你想要什么价值?如果
'K_P_1'
不存在,您想要什么值?如果'K_P_1'不存在,结果应该为空。由于查询中的限制,不可能有多个键。根据我从问题中收集到的信息,我更喜欢这个答案。
SELECT tab.*,
FIRST_VALUE(Text IGNORE NULLS) OVER(PARTITION BY Key ORDER BY Code) AS FamilyText
FROM tab;
with s (Key, Code, Text) as (
select '11K', 'K_P_1', 'text' from dual union all
select '11K', 'K_P_2', null from dual union all
select '11K', 'K_P_3', null from dual union all
select '12K', 'K_P_1', 'text2' from dual union all
select '12K', 'K_P_2', null from dual union all
select '12K', 'K_P_3', null from dual)
select s.*, lag(text ignore nulls, 1, text) over (partition by key order by code) FamilyText
from s;
KEY CODE TEXT FAMIL
--- ----- ----- -----
11K K_P_1 text text
11K K_P_2 text
11K K_P_3 text
12K K_P_1 text2 text2
12K K_P_2 text2
12K K_P_3 text2
6 rows selected.