Немного сложно, но попробуйте это КАК ЕСТЬ:
create table Products (
ID int not null generated always as identity primary key
, Detail1 int not null
, Detail2 int not null
, Detail3 int not null
, Customer int not null
, OrderingCode int not null
, Date date not null
) in userspace1;
create table Orders(
P_ID int not null
, Quantity int not null
, Date date not null
, orderNumber int not null
, constraint orders_fk foreign key (p_id) references Products (id)
) in userspace1;
with r (OrdNumber, Detail1, Detail2, Detail3, Date, Quantity, Customer, OrderingCode) as (values
(12345, 122, 123, 12, '12/12/2018', 2, 123, 567)
, (12345, 122, 123, 15, '12/12/2018', 2, 123, 567)
, (12345, 516, 123, 63, '12/12/2018', 5, 123, 567)
, (12345, 617, 123, 14, '12/12/2018', 7, 123, 567)
, (12345, 617, 123, 14, '12/12/2018', 4, 123, 567)
, (12345, 617, 123, 17, '12/12/2018', 2, 123, 567)
, (12345, 745, 123, 43, '12/12/2018', 2, 123, 567)
)
, p as (
select ID, Quantity, Date, ordNumber
from new table (
insert into products (Detail1, Detail2, Detail3, Customer, OrderingCode, Date)
include (OrdNumber int, Quantity int)
select Detail1, Detail2, Detail3, Customer, OrderingCode, Date, OrdNumber, Quantity
from (
select Detail1, Detail2, Detail3, Customer, OrderingCode, Date, OrdNumber, Quantity
, rownumber() over (partition by Detail1, Detail2, Detail3 order by Quantity desc) rn_
from r
) where rn_=1
)
)
select count(1)
from new table (
insert into Orders (P_ID, Quantity, Date, orderNumber)
select ID, Quantity, Date, ordNumber
from p
);
В предложении 1-й WITH
(обозначается r
) есть набор результатов, который вы получаете по запросу.
Пара выбирает из data-change operation
используется тогда.
1-я единица (упоминаемая как p
) вставляет необходимые строки в Products
и генерируется ID
s для этих строк.
2-я (самая последняя) вставляет строки в Orders
, используя сгенерированные идентификаторы и другие необходимые поля.