简体   繁体   English

在SQL Server 2008中做PIVOT表

[英]Doing a PIVOT table in SQL Server 2008

Seems like it should be really easy to change this one row data: 似乎很容易更改这一行数据:

SalesTotal Refunds  Discount Taxes  
63093.05   -102.52  3905.11  2523.32

Into this: 变成这个:

SalesTotal  63093.05
Refunds      -102.52
Discount     3905.11
Taxes        2523.32

Using the PIVOT in SQL. 在SQL中使用PIVOT。 But... in all the examples I found; 但是...在我发现的所有示例中;

http://www.izenda.com/Site/KB/FAQ/How-do-I-create-a-pivot-table-in-Microsoft-SQL- http://blog.sqlauthority.com/2008/05/22/sql-server-pivot-table-example/ http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server/ http://msdn.microsoft.com/en-us/library/ms177410(SQL.105).aspx Etc.... http://www.izenda.com/Site/KB/FAQ/How-do-I-create-a-pivot-table-in-Microsoft-SQL- http://blog.sqlauthority.com/2008/05/ 22 / sql-server-pivot-table-example / http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server/ http://msdn.microsoft.com/ zh-CN / library / ms177410(SQL.105).aspx等...

there was the need of doing addition aggregates in the PIVOT command. 需要在PIVOT命令中进行附加聚合。
All I am wanting to do is turn the table on its side. 我只想把桌子转过来。

Any way of doing that? 有什么办法吗?

You should be looking for UNPIVOT instead. 您应该寻找UNPIVOT Here is a way of getting the results you want with CROSS APPLY (this assumes that all of your columns have a compatible data type): 这是通过CROSS APPLY获得所需结果的一种方法(假定您所有列都具有兼容的数据类型):

SELECT  x.Col,
        x.Value
FROM YourTable t
CROSS APPLY 
(
    VALUES
        ('SalesTotal', t.SalesTotal),
        ('Refunds', t.Refunds),
        ('Discount', t.Discount),
        ('Taxes', t.Taxes)
) x(Col, Value);

You need UNPIVOT not PIVOT to rotate columns into rows 您需要UNPIVOT而不是PIVOT才能将列旋转成行

SELECT Type, value from
(SELECT * from Table1) T
UNPIVOT
( value for Type in ( [SalesTotal], [Refunds], [Discount], [Taxes])
) unpvt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM