INSERT新行合并类似的行

时间:2014-03-18 22:05:04

标签: sql sql-server-2008 clone ssms consolidation

这是我需要完成的事情:

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

New Row将代表合并订单。

进入同一地址的两个订单合并为一个

插入前的示例表

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 ;

提前感谢您的回答

1 个答案:

答案 0 :(得分:0)

您的订单表应该包含更多列,以显示订单是合并,是否有资格进行合并,或者是否已合并。这是我提出的解决方案,它增加了列。所有推断的列都在CAPS中。

--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)
相关问题