1

我正在尝试从一个帮助台软件迁移到另一个,其中一部分是迁移我们的票证历史数据库,我将其导出到 Excel 电子表格,然后导入 SQL Server 数据库。

表格的当前格式如下:

列标题:

Description: Initial ticket text  
ticketnum: Ticket number  
subject: Ticket subject header  
value: ticket comment  

如果需要:

Description: nvarchar(max)  
ticketnum: float  
subject: nvarchar(max)  
value: nvarchar(max)  

编辑:如要求的示例数据:

Description            TicketNum     Subject                       Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded
Our computer exploded   10020        CPU Explosion        The computer is a dell
Virus Found             10021        Virus                We need help with a virus

我希望它变成:

Description            TicketNum     Subject              Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded; The computer is a dell
Virus Found             10021        Virus                We need help with a virus

每一行都是工单的一个新条目,因此 value 字段始终是唯一的,而每个工单号的描述和 value 保持不变。所以我希望根据票号字段合并行,保留/合并值字段的所有数据,并且只保留主题和描述字段的一个值。我已经看到了许多与我的场景接近的问题,但没有一个匹配,遗憾的是我对 SQL 知之甚少,并且不足以根据我所看到的单独推断出这一点。

非常感谢你。

编辑 2:修改后的代码,运行但不合并,产生一个空表:

declare @tmpTable table ([Description] nvarchar(max), niceid float, 
[Subject] nvarchar(max), [Value] nvarchar(max))

SELECT * INTO tmpTable FROM sheetnew$

declare @newTable table ([Description] nvarchar(max), niceid float, 
[Subject] nvarchar(max), [Value] nvarchar(max))


insert into @newTable
select distinct 
    x.[Description]
    ,x.niceID
    ,x.[Subject]
   ,[Value] = stuff((
          select '; ' + y.[Value]
          from @tmptable y
          where x.niceid = y.niceid
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @tmptable x
4

1 回答 1

0

这是一种使用方法STUFF

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_WARNINGS ON
GO
SET ANSI_PADDING ON
GO

declare @table table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @table
values
('Our computer exploded',10020,'CPU Explosion','Our computer exploded'),
('Our computer exploded',10020,'CPU Explosion','The computer is a dell'),
('Virus Found',10021,'Virus','We need help with a virus')





declare @newTable table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @newTable
select distinct 
    x.[Description]
    ,x.TicketNum
    ,x.[Subject]
    ,[Value] = stuff((
          select '; ' + y.[Value]
          from @table y
          where x.TicketNum = y.TicketNum
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @table x


select * from @newTable
于 2017-11-13T21:03:51.620 回答