使用SQL Query将一列拆分为多列

时间:2017-12-05 13:45:03

标签: sql sql-server

我想使用SQL Query

将一列拆分为多列

数据不仅选择它存储到其他列

我有这种类型的表:

 [ID]    [DATE_TIME]           [VALUE]

 1       2014-09-24 11:59:00   Record No = 00> 40 >Record No = 01> 40 >Record No = 02> 71>

我需要分数记录 像这样:

 [ID]    [DATE_TIME]          [VALUE1]              [VALUE2]    

 1       2014-09-24 11:59:00  Record No = 00> 40 >  Record No = 01> 40 >
 [VALUE3]                [VALUE4]
 Record No = 02> 71>     NULL

1 个答案:

答案 0 :(得分:0)

您可以使用xml和pivot来实现此目的。试试这个:

SELECT * 
FROM   (SELECT A.[ID], 
               'VALUE' 
               + Cast(Row_number() OVER(partition BY [ID] ORDER BY ID ) AS 
               VARCHAR(4)) 
                      AS rowid, 
               A.[DATE_TIME], 
               A.[VALUE], 
               split.a.value('.', 'VARCHAR(100)') 
                      AS [VALUES] 
        FROM   (SELECT [ID], 
                       [DATE_TIME], 
                       [VALUE], 
                       Cast ('<M>' 
                             + Replace([VALUE], '>Record No', '</M><M>Record No' 
                             ) 
                             + '</M>' AS XML) AS String 
                FROM   #temp) AS A 
               CROSS apply string.nodes ('/M') AS Split(a)) SourceTable 
       PIVOT ( Max([VALUES]) 
             FOR ROWID IN([VALUE1], 
                          [VALUE2], 
                          [VALUE3],
                          [VALUE4]) ) AS pivottable 

动态地,您可以使用以下脚本:

CREATE TABLE #temp 
  ( 
     [ID]        INT IDENTITY(1, 1), 
     [DATE_TIME] DATETIME, 
     [VALUE]     VARCHAR(255) 
  ) 

INSERT INTO #temp 
            (DATE_TIME, 
             VALUE) 
VALUES     ('2014-09-24 11:59:00', 
            'Record No = 00> 40 >Record No = 01> 40 >Record No = 02> 71>') 

SELECT A.[ID], 
       'VALUE' 
       + Cast(Row_number() OVER(partition BY [ID] ORDER BY ID ) AS VARCHAR(4)) 
       AS rowid, 
       A.[DATE_TIME], 
       A.[VALUE], 
       split.a.value('.', 'VARCHAR(100)') 
       AS [VALUEs] 
INTO   #temp1 
FROM   (SELECT [ID], 
               [DATE_TIME], 
               [VALUE], 
               Cast ('<M>' 
                     + Replace([VALUE], '>Record No', '</M><M>Record No') 
                     + '</M>' AS XML) AS String 
        FROM   #temp) AS A 
       CROSS apply string.nodes ('/M') AS Split(a) 

DECLARE @cols  AS NVARCHAR(max), 
        @query AS NVARCHAR(max) 

SET @cols = Stuff((SELECT DISTINCT ',' + Quotename(c.ROWID) 
                   FROM   #temp1 c 
                   FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '' 
            ) 

SET @query = ' select *
                from
                (
                    select * 
                    from #temp1
                ) SourceTable
                pivot
                (
                    max([VALUEs])
                    for rowid in(' + @cols + ')
                ) as PivotTable'

EXECUTE(@query)