我有2张桌子。我需要从表一中选择一些id并基于一个条件并插入表2.第二列必须来自tableA但基于不同的条件
表A
NC 1
NC 2
SC 3
SC 4
表B
1 100
1 200
2 100
2 200
我想在表B中插入行,所以它看起来像这样....
1 100
1 200
2 100
2 200
3 100
3 200
4 100
4 200
我根据状态condtion ='SC'从表A中选择3和4,现在我想知道如何选择NC有的100和200的值......
对不起,如果我没有措辞正确
答案 0 :(得分:2)
-- sample data
create table tbla (code char(2), id int);
insert into tbla values ('NC', 1);
insert into tbla values ('NC', 2);
insert into tbla values ('SC', 3);
insert into tbla values ('SC', 4);
create table tblb (id int, value int);
insert into tblb values (1, 100);
insert into tblb values (1, 200);
insert into tblb values (2, 100);
insert into tblb values (2, 200);
-- your query to INSERT the new rows into tblb
insert into tblb
select x.id, y.value
from
(
select distinct a.id
from tbla a
where a.code = 'SC'
) x
cross join
(
select distinct b.value
from tbla a
join tblb b on a.id = b.id
where a.code = 'NC'
) y
left join tblb b on b.id = x.id and b.value = y.value
where b.id is null;
答案 1 :(得分:0)
您可以通过以下查询执行此操作:
Select a.id, b.value
from "Table A" a
join "Table B" b
on b.id=1 --This condition pick the two first rows on table B.
where a.condtion = 'SC'
这不是一个优雅的解决方案,但它有效。