将列旋转为行,反之亦然

时间:2017-06-15 19:33:50

标签: sql tsql pivot

我正试图转入列,但我一直遇到错误。我不知道自己做错了什么。我尝试了下面的代码但是我继续在" FOR"下面获得红色波浪线。和括号中的第一个单词。这是我的代码:

select d.City,d.Geographic_Region_Name, d.Site_Type
from Site_Profile as d
pivot
(City for Geographic_Region_Name in (City,Geographic_Region_Name,site_type) as pivotable;

1 个答案:

答案 0 :(得分:2)

Pivot用于将聚合行转换为列。来自documentation

SELECT <non-pivoted column>,  
    [first pivoted column] AS <column name>,  
    [second pivoted column] AS <column name>,  
    ...  
    [last pivoted column] AS <column name>   FROM  
    (<SELECT query that produces the data>)   
    AS <alias for the source query>   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>   
    <optional ORDER BY clause>;

您需要在SUM之前使用汇总函数(COUNTMAXMINFOR等。

相关问题