SQL数据透视转换

时间:2017-02-25 10:04:56

标签: sql sql-server pivot

我想使用一个查询来返回从表FloatNAR800中的行转换而来的列,我有这个代码,但对我来说不起作用。有什么想法吗?

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'

附近的语法不正确

但我不知道自己做错了什么......

1 个答案:

答案 0 :(得分:0)

您缺少代码... pivot语句不会以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

我建议你先让Pivot工作,然后把它变成动态的sql。