ms sql pivot不起作用

时间:2016-10-14 22:17:51

标签: sql-server pivot transpose unpivot

我试图将一个简单的表从行转换为具有两个字符串变量的列。我通过网络上的几个例子没有成功。行数会有所不同,所以我需要动态转置表。以下代码至少不会产生错误但不会生成结果!

样本表

    create table #Encabezado
    (
    NodeName nvarchar(100),
    NodeValue nvarchar(100)
    )

INSERT INTO #Encabezado (NodeName, NodeValue) VALUES
('RUTEmisor','88888888-8'),
('RznSoc','EMPRESA DE PRUEBA'),
('GiroEmis','Informatica'),
('Acteco','1'),
('CdgSIISucur','59529595'),
('DirOrigen','Teatinos 120'),
('CmnaOrigen','Santiago'),
('CiudadOrigen','Santiago')
GO

非透明代码

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

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = '#Encabezado' and
                 C.column_name like '%Name'
           for xml path('')), 1, 1, '')

set @query 
  = 'select NodeName,
        Nodevalue
     from #Encabezado
     unpivot
     (
        NodeName
        for NodeName in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

Sequelspear曾经说过:"对于Pivot或UnPivot,这就是问题所在。"

declare @cols NVARCHAR(MAX) = stuff((select ','+quotename(Nodename) from #Encabezado group by Nodename for xml path('')),1,1,'');

declare @query NVARCHAR(MAX) = 'select * from #Encabezado pivot (max(NodeValue) for NodeName IN ('+ @cols +')) pvt';

exec sp_executesql @query;

答案 1 :(得分:0)

动态转动

Declare@Cols AS NVARCHAR(MAX),@SQL  AS NVARCHAR(MAX);

Set @Cols = Stuff((Select Distinct ',' + QuoteName(NodeName) 
                    From  #Encabezado 
                    For XML Path(''), Type
                   ).value('.', 'varchar(max)'),1,1,'')

Set @SQL = 'Select * From #Encabezado
            Pivot (
                   max(NodeValue)
                   For [NodeName] in (' + @Cols + ')
                  ) p '

Exec (@SQL)

<强>返回

enter image description here

现在,要取消投票,请考虑以下事项:

Declare @User table (ID int,Active bit,First_Name varchar(50),Last_Name varchar(50),EMail varchar(50))
Insert into @User values
(1,1,'John','Smith','john.smith@email.com'),
(2,0,'Jane','Doe'  ,'jane.doe@email.com')

Declare @XML xml = (Select * from @User for XML RAW)

Select ID     = r.value('@ID','int')
      ,Active = r.value('@Active','bit')
      ,Item   = attr.value('local-name(.)','varchar(100)')
      ,Value  = attr.value('.','varchar(max)') 
 From  @XML.nodes('/row') as A(r)
 Cross Apply A.r.nodes('./@*') AS B(attr)
 Where attr.value('local-name(.)','varchar(100)') not in ('ID','Active')

返回

enter image description here