如何将行转换为sql server中的列

时间:2014-12-13 03:00:42

标签: sql sql-server xml sql-server-2008 xml-parsing

我已经从xml生成了一个临时表,它具有以下结构

   column1    column2
     id         1234
     code      ukjk
     .
     .
      there will be another 60 rows again
     id         4586
     code       ouiu 
     .
     . 
       there will be another 60 rows again
     id          78545
     code         khdsjf

     like this there will be 15 id's in the table

现在我想将行转换为像

这样的列

我不希望所有60个我只需要其中的5个

      id   code   vdb_id    guid ....
      1234
      4586
      78545

我也附上了XML文件图片..

我使用过枢轴功能

   IF OBJECT_ID('tempdb..#xml_final') IS NOT NULL DROP TABLE #xml_final
   CREATE TABLE #xml_final (rownum int, Project_id int, Project_Name varchar(60),     Project_manager_id int, Updated_date varchar(60) )

    insert into  #xml_final
    SELECT * FROM

  (

      SELECT xmlData.Result.value('v[1]','VARCHAR(200)') AS A,
       xmlData.Result.value('n[1]','VARCHAR(200)') AS B,
     ROW_NUMBER() over(PARTITION BY xmlData.Result.value('n[1]','VARCHAR(200)')
          order by xmlData.Result.value('v[1]','VARCHAR(200)')) AS Num
    FROM @xmlData.nodes('//result/rows/row/f') xmlData(Result)

  ) AS A
   Pivot (Min(A) FOR B IN ([id] ,
                    [summary],
                    [manager_id],
                    [ts]
                    )
   ) piv     

但它无法正常工作..我遇到了不匹配的错误

例如

     id 1234  i am getting code as ouiu

output2表将有3列

    row_num    key2    item_value
        1    id        1234
        5   proj_id     7655
        9   task_name    kfhkjfdhg
       21   id         5455
       25   proj_id     6789797
       29   task_name   dsyhuiyfhdi

和key2将只包含这3个列名

我想要的输出是,

    id     proj_id    task_name

  1234     7655        kfhkjfdhg
  5455   6789797    dsyhuiyfhdi



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

    select @cols = STUFF((SELECT DISTINCT  ',' + QUOTENAME(key2) 
                from #output_2
                group by key2, row_num
                order by row_num
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

   set @query = N'SELECT ' + @cols + N' from 
         (
            select item_value, key2
            from #output_2
        ) x
        pivot 
        (
            max(item_value)
            for key2 in (' + @cols + N')
        ) p '

  print @query
  exec sp_executesql @query;

更新了查询

     DECLARE @columns VARCHAR(max)='',
    @sql     NVARCHAR(max)

     SELECT @columns += COL
      FROM   (SELECT DISTINCT '[' + Isnull(key2, '') + '],' col
    FROM   #output_2
    WHERE  item_value IS NOT NULL) a   

     SELECT @columns = LEFT(@columns, Len(@columns) - 1)


      SET @sql ='SELECT rownum,' + @columns + '
      FROM   (SELECT Row_number()OVER(PARTITION BY key2 ORDER BY item_value) rownum,
               *
        FROM   #output_2)a
       PIVOT(Max(item_value)
            FOR key2 IN(' + @columns + ')) piv '

            Print @sql

       EXEC Sp_executesql @sql 

更新了查询2:

      IF OBJECT_ID('tempdb..#output_3') IS NOT NULL DROP TABLE #output_3
      CREATE TABLE #output_3 (   row_id int, row_num int , task_id int, project_id int, task_name   varchar(200) )

     insert into #output_3
     SELECT Row_number() over (ORDER BY (select null)) row_id ,  rownum,(id),(project_id),(summary)
       FROM   (SELECT Row_number()OVER(PARTITION BY key2 ORDER BY (select null))     rownum,
               *
        FROM   #output_2)a
       PIVOT(Max(item_value)
            FOR key2 IN([id],[project_id],[summary])) piv


      select row_id, task_id, task_name, project_id  from   #output_3  

输出:

enter image description here

INSERT QUERY

      IF OBJECT_ID('tempdb..#output') IS NOT NULL DROP TABLE #output
   CREATE TABLE #output ( id int ,key2 varchar(50), item_value varchar(200) )

   insert into #output 
      select
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as SNumber, 
     key2 = Item2.value('(n)[1]','varchar(50)'),
     ItemValue = Item2.value('(v)[1]','varchar(50)')
      from
       @xmlData.nodes('/result/rows') as T(Item)
     cross apply
     item.nodes('row/f') as T2(Item2)

如何解决这个问题..

how can i read multiple xml values from URL through t-sql

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

试试这个。像这样更改你的Pivot Query

create table #output(key2 varchar(50),item_value varchar(50))

insert #output
values 
('id','1234'),('code','ukjk'),('GUID','DFG'),
('SRC',null),('TS',null),('workspcd','3245'),
('id','4586'),('code','ouiu'),('GUID','ff'),
('SRC',null),('TS',null),('workspcd','2233'),
('id','78545'),('code','khdsdf'),('GUID','dffff'),
('SRC',null),('TS',null),('workspcd','3234')

SELECT rownum,[id],[code],[GUID],[workspcd]
FROM   (SELECT Row_number()OVER(PARTITION BY key2 ORDER BY item_value) rownum,
               *
        FROM   #output)a
       PIVOT(Max(item_value)
            FOR key2 IN([id],[code],[GUID],[SRC],[TS],[workspcd])) piv 

更新:动态投放

DECLARE @columns VARCHAR(max)='',
        @sql     NVARCHAR(max)

SELECT @columns += COL
FROM   (SELECT DISTINCT '[' + Isnull(key2, '') + '],' col
        FROM   #output
        WHERE  item_value IS NOT NULL) a

SELECT @columns = LEFT(@columns, Len(@columns) - 1)

SET @sql ='SELECT rownum,' + @columns + '
    FROM   (SELECT Row_number()OVER(PARTITION BY key2 ORDER BY item_value) rownum,
                   *
            FROM   #output)a
           PIVOT(Max(item_value)
                FOR key2 IN(' + @columns + ')) piv '

EXEC Sp_executesql @sql

输出:

rownum  id      code    GUID    workspcd
------  ----    ------  -----   --------
1       1234    khdsdf  dffff   2233
2       4586    ouiu    DFG     3234
3       78545   ukjk    ff      3245

更新以删除NULL值

SELECT Row_number()
         OVER (
           ORDER BY (SELECT NULL)) row_id,
       rownum,
       Max(id)                     id,
       Max(project_id)             project_id,
       Max(summary)                summary
FROM   (SELECT Row_number()
                 OVER(
                   PARTITION BY key2
                   ORDER BY (SELECT NULL)) rownum,
               *
        FROM   #output_2)a
       PIVOT(Max(item_value)
            FOR key2 IN([id],
                        [project_id],
                        [summary])) piv
GROUP  BY rownum