Sql-Server

如何在這裡使用 PIVOT?

  • January 11, 2017

我有這張桌子

+--------+--------------+----------------+--------------+----------------+
|  XPK   | First_count  |  First_amount  | Second_count |  Second_amount |
+--------+--------------+----------------+--------------+----------------+
|      1 |     10       |       2000     |     20       |       5000     | 
+--------+--------------+----------------+--------------+----------------+

需要得到這樣的結果,求和和透視:

+-------------+------------+
|Total_count  |     30     |
|Total_amount |    7000    |
+-------------+------------+

我需要使用樞軸,但如何?

使用 MS SQL Server 2014

老實說,對於這種需要,我不會使用pivot,我會簡單地:

select XPK, 'Total_count', First_count + Second_count
from my_table
union
select XPK, 'Total_amount', First_amount + Second_amount
from my_table

如果你真的想用pivot你可以試試:

select XPK, kpi, total
from (
select XPK,  First_count + Second_count as Total_count, First_amount + Second_amount as Total_amount
from my_table
) t
unpivot (total for kpi in(Total_count, Total_amount)) tt

但也許你的問題比你描述的更複雜……

引用自:https://dba.stackexchange.com/questions/160716