2017-02-25 119 views
0

我想使用查询来返回从表FloatNAR800与透视表中的行转换的列我有这段代码但不适用于我。任何想法 ?SQL数据透视表变换

declare @nume_coloane as nvarchar(max), 
     @dynamic_pivot_query as nvarchar(max) 

set @nume_coloane = STUFF ((select ',' + QUOTENAME(TagIndex) 
          from (select distinct TagIndex from FloatN2_NAR800) sub 
          order by TagIndex 
          for xml path(''), type).value('.', 'nvarchar(max)') 

set @dynamic_pivot_query = 'select DateAndTime,' + @nume_coloane + 
          'from 
           (select DateAndTime, TagIndex, Val 
           from FloatN2_NAR800) x 
          pivot' 

当我想要创建这个查询会出现一个错误:

附近有语法错误关键字“SET”

,但我不知道我做错了.. 。

回答

0

您缺少代码...枢轴语句dos不以Pivot关键字结束。

You code then... 
    PIVOT 
     (
         <aggregation function>(<column being aggregated>) 
     FOR 
     [<column that contains the values that will become column headers>] 
         IN ([first pivoted column], [second pivoted column], 
         ... [last pivoted column]) 
     ) AS <alias for the pivot table> 

到这里看看:https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

我劝你得到枢轴第一个工作日,然后使之成为一个动态SQL。