在SQL中,有没有办法添加不存在的行(基于某些组合)。
所有没有值的行:
Col-a Col-a
Col-a Col-b
Col-a Col-c
...
数据库:
Col-a Col-a Val-a
Col-a Col-b Val-b
Col-b Col-a Val-c
Col-b Col-b Val-d
...
假设db中存在 Col-a Col-c 的行,我想添加Col-a, Col-c, 0
,只是插入一个零值的缺失行。
示例:
1,1,50
1,2,100
2,2,100
所以这里我们缺少2,1因此加上2,1,0。 我将给出一个[1,2],其中两个值都应该存在。
预期产出:
1,1,50
1,2,100
2,1,0
2,2,100
有一种简单的方法吗?
答案 0 :(得分:0)
你应该把它们“联合”起来......
select '' col-a, '' col-b, '' col-c, [null your_table.fields]
union
select '' col-a, '' col-b, '' col-c, your_table.*
from your_table
评论后的 更新以及原始问题中的结算:
你可以尝试这个sql语句..
select THeaders.col_a, THeaders.col_b, TSrcValues.col_c
from
(
select 1 as col_a, 1 as col_b, 0 as col_c from dual
union
select 1 as col_a, 2 as col_b, 0 as col_c from dual
union
select 1 as col_a, 3 as col_b, 0 as col_c from dual
union
select 2 as col_a, 1 as col_b, 0 as col_c from dual
union
select 2 as col_a, 2 as col_b, 0 as col_c from dual
union
select 2 as col_a, 3 as col_b, 0 as col_c from dual
)THeaders
left join
(
select TSrc.*
from
(
select
case when YourValue = 100 then 1 else case when YourValue = 200 then 2 else case when YourValue = 300 then 3 else 0 end end end col_a,
case when YourValue = 100 then 1 else case when YourValue = 200 then 2 else case when YourValue = 300 then 3 else 0 end end end col_b,
YourValue as col_c
from YourTable
) TSrc
where TSrc.col_a <> 0 or TSrc.col_b <> 0
) TSrcValues
on THeaders.col_a = TSrcValues.col_a and THeaders.col_b= TSrcValues.col_b
;
您应该在“case when”子句中个性化您的值范围
答案 1 :(得分:0)
您的示例需要更清晰。但是,如果我理解正确,您需要找到第一列的所有唯一值,并将其与第二列的所有唯一值组合,如果该组合不存在,则插入该行:
Release
Here is a SQLFiddle显示SELECT组件正常工作