-- 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;
你的邏輯不清楚。你如何用'4'將'100'與'3'和'200'聯繫起來?如果行數多於或少於兩行,會發生什麼? – 2013-05-01 19:56:27
對不起......我的問題不對。 – user1410867 2013-05-01 20:03:57
我已更正我的問題 – user1410867 2013-05-01 20:09:15