0

这是我需要完成的事情:

通过组合来自同一个表 ( t_order ) 的两行或多行在t_order中插入一个新行,其中除 order_id (Identity) 和 order_number 之外的所有值都相同

新行将代表一个合并的订单。

发往同一地址的两个订单合并为一个

插入前的示例表

order_id   order_number   ship_addrs1    ship_to_zip
--------   ------------   -----------    -----------
   1       ABC001         111 1st St     11111
   2       ABC002         123 Main St    12345  <--- Source Row 
   3       ABC003         123 Main St    12345  <--- Source Row
   4       ABC004         111 2nd St     11111

插入后的结果(必须保留源订单)

order_id   order_number   ship_addrs1    ship_to_zip
--------   ------------   -----------    -----------
   1       ABC001         111 1st St     11111
   2       ABC002         123 Main St    12345
   3       ABC003         123 Main St    12345 
   4       ABC004         111 2nd St     11111
   5       ABC005         123 Main St    12345  <--- New Row

我考虑过使用以下代码来完成此操作,但不确定合并三行需要做什么。

SELECT * INTO    tmp_order_cosolidation 
  FROM           t_order 
  WHERE          order_id = 1 AND order_number = ABC002

ALTER TABLE      tmp_order_cosolidation 
  DROP COLUMN    order_id, ordern_number

INSERT INTO      t_order 
  SELECT             * 
  FROM           tmp_order_cosolidation;

DROP TABLE       tmp_order_cosolidation ;

预先感谢您的回答

4

1 回答 1

0

您的订单表应该有更多的列来显示订单是合并的、符合合并条件的还是已经合并的。这是我提出的解决方案,其中添加了列。所有推断的列都使用大写字母。

--VIEW ROWS TO INSERT
select count(order_id),ship_addrs1,ship_to_zip2
from t_order
where CONSOL_ELIGIBLE = 'Y' and CONSOL_COMPLETED = 'N'
group by ship_addrs1,ship_to_zip2
having count(order_id) > 1

--TEMP TABLE FOR INSERT
declare @tmptable TABLE (total_orders int,ship_addrs1 nvarchar(50),ship_to_zip2 nvarchar(50),CONSOL_ELIGIBLE nvarchar(1))
insert into @tmptable (total_orders, ship_addrs1,ship_to_zip2,CONSOL_ELIGIBLE)
(select count(order_id),ship_addrs1,ship_to_zip2,'N'
from t_order
where CONSOL_ELIGIBLE = 'Y' and CONSOL_COMPLETED = 'N'
group by ship_addrs1,ship_to_zip2
having count(order_id) > 1)

--INSERT FROM TEMP TABLE
insert into ORDER_TABLE (total_orders, ship_addrs1,ship_to_zip2,CONSOL_ELIGIBLE)
(select total_orders, ship_addrs1,ship_to_zip2,CONSOL_ELIGIBLE
from @tmptable)
于 2014-03-18T22:46:55.013 回答