如何在数据更改时将单个列拆分为SQL Server中的多个列?

时间:2015-08-06 04:39:56

标签: sql-server split

我有一个事件表,如下所示:

CREATE TABLE [dbo].[Event](
    [EventId] [int] NULL,
    [Event] varchar(100) NULL,
    [EventDate] [datetime] NULL,
    [ItemNo] [varchar](20) NULL
) 

GO

insert into [Event]
VALUES (1,'TestEvent','7/2/2015','Item1')
GO

insert into [Event]
VALUES (1,'TestEvent','7/3/2015','Item1')
GO

insert into [Event]
VALUES (1,'TestEvent','7/4/2015','Item1')
GO

insert into [Event]
VALUES (1,'TestEvent','7/5/2015','Item1')
GO

insert into [Event]
VALUES (2,'TestEvent02','7/7/2015','Item1')
GO

insert into [Event]
VALUES (2,'TestEvent02','7/8/2015','Item1')
GO

insert into [Event]
VALUES (2,'TestEvent02','7/9/2015','Item1')
GO

SELECT * FROM DBO.Event
GO

Event       EventDate   ItemNo
TestEvent   7/2/2015  Item1
TestEvent   7/3/2015  Item1
TestEvent   7/4/2015  Item1
TestEvent   7/5/2015  Item1
TestEvent02 7/7/2015  Item1
TestEvent02 7/8/2015  Item1
TestEvent02 7/9/2015  Item1

现在,我希望在数据更改时将事件字段拆分为多个字段,在本例中为" TestEvent02"应该显示为新字段:

请注意,可能有多个事件,因此事件数量不固定,因此应动态计算要生成的字段数。

Output:
------

Event1       Event2     EventDate   ItemNo
TestEvent               7/2/2015    Item1
TestEvent               7/3/2015    Item1
TestEvent               7/4/2015    Item1
TestEvent               7/5/2015    Item1
            TestEvent02 7/7/2015    Item1
            TestEvent02 7/8/2015    Item1
            TestEvent02 7/9/2015    Item1

2 个答案:

答案 0 :(得分:0)

我认为这是个糟糕的主意。你需要这样做的原因是什么?我认为,最好将事件存储在一列中,有选择索引,或者可能有一个分区表。

答案 1 :(得分:0)

试试这个:

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(event)
  FROM (SELECT p.Event FROM dbo.Event AS p  
  GROUP BY p.Event) AS x;
SET @sql = N'
SELECT p.ItemNo,p.EventDate,' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT p.ItemNo,p.EventDate,Event
   FROM dbo.Event AS p

) AS j
PIVOT
(
  max(Event) FOR Event IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;