合并来自多行的数据

San*_*ndy 6 pivot t-sql sql-server-2012

我在处理查询时相对较新,所以让我提前道歉。这是我将使用的 SQL Server 2012。这些数据已通过每晚从 Excel 导入的方式导入临时表。我需要将此数据从该表移动到我们的主硬件表中,并确保在检查时插入任何新数据以确保它更新任何旧数据。我会提供尽可能多的信息,请耐心等待。

字段名称是:

|Ticket_Num | Name | Worker | date1 | Serial | Part | Description1 | Type1 | Eqmt_Type |
Run Code Online (Sandbox Code Playgroud)

我需要将它们带入具有以下内容的表中:

   |Event_NUM|Name|Install_Date|Pull_Date|Install_Tech|Pull_Tech| PMP1_Desc|PMP1_Part|PMP1_Serial|PMP2_Desc|PMP2_Part|PMP2_Serial|PMP3_Desc|PMP3_Part|PMP3_Serial|Motor1_Desc|Motor1_Serial|Motor1_Part|Motor2_Desc| Motor2_Serial| Cab1_Disc|Cab1_Part|Cab1_Serial|Cab2_Desc|Cab2_Part|Cab2_Serial|Dis1_Desc|Dis1_Part|Dis1_Serial|Dis2_Desc|Dis2_Part|Disc2_Serial|
Run Code Online (Sandbox Code Playgroud)

这是 SQL Fiddle 的示例,其中包含从 Excel 中提取的数据: SQL Fiddle for data to be insert

这是 SQL Fiddle 和我想要的示例:SQL Fiddle example of what I would like

Mar*_*rco 0

我会选择两步解决方案。我使用简单的 SQL。您可以使用正确的名称和字段。首先我会更新现有的行:

update tab1
set tab1.field = tab1.field + tmp1.field
from table1 tab1 inner join temp1 tmp1 on tab1.key=tmp1.key;
Run Code Online (Sandbox Code Playgroud)

其次,我将插入所有不存在的行:

insert into table1 (key, field)
select key, field
from   temp1
where  tmp1 not in (select key
                    from   table1);
Run Code Online (Sandbox Code Playgroud)

要完成,您必须截断temp1表并提交。