sql pivot(行转列) 和unpivot(列转行)的用法

Posted Dolen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql pivot(行转列) 和unpivot(列转行)的用法相关的知识,希望对你有一定的参考价值。

1、PIVOT用法(行转列)

select * from Table_Score as a
pivot (sum(score) for a.name in ([语文],[数学],[外语],[文综],[理综])) as b

数据:

id    name    score
1    语文    100
2    数学    95
3    外语    100
4    文综    250
5    理综    300

 

结果:

id    语文    数学    外语    文综    理综
1    100    NULL    NULL    NULL    NULL
2    NULL    95    NULL    NULL    NULL
3    NULL    NULL    100    NULL    NULL
4    NULL    NULL    NULL    250    NULL
5    NULL    NULL    NULL    NULL    300

 

 

2、UNPIVOT用法(列转行)

select orders,weekend from
(select week1,week2,week3,week4,week5 from [dbo].[Table_Week]) a
unpivot(orders for weekend in (week1,week2,week3,week4,week5)) as b

数据:

week1    week2    week3    week4    week5
11    22    33    44    55
22    33    44    55    66
33    44    55    66    77
44    55    66    77    88

 

结果:

orders    weekend
11    week1
22    week2
33    week3
44    week4
55    week5
22    week1
33    week2
44    week3
55    week4
66    week5
33    week1
44    week2
55    week3
66    week4
77    week5
44    week1
55    week2
66    week3
77    week4
88    week5

 

以上是关于sql pivot(行转列) 和unpivot(列转行)的用法的主要内容,如果未能解决你的问题,请参考以下文章

sql的行转列(PIVOT)与列转行(UNPIVOT)

sql的行转列(PIVOT)与列转行(UNPIVOT)

sql pivot(行转列) 和unpivot(列转行)的用法

SQL 行转列 列转行 PIVOT UNPIVOT

SqlServer PIVOT函数快速实现行转列,UNPIVOT实现列转行

T-Sql语法:行转列(pivot)和列转行(unpivot)