转自:http://blog.sina.com.cn/s/blog_5ef755720100cyo3.html

pivot函数:

create table test(id int,name varchar(20),quarter int,profile int)
insert into test values(1,'a',1,1000)
insert into test values(1,'a',2,2000)
insert into test values(1,'a',3,4000)
insert into test values(1,'a',4,5000)
insert into test values(2,'b',1,3000)
insert into test values(2,'b',2,3500)
insert into test values(2,'b',3,4200)
insert into test values(2,'b',4,5500)

select * from test    --创建表test

现在需要把quarter 从1列数据变成4列数据  效果如:

把一列拆成几列这时候就能使用pivot函数很简单的实现

select * from test
pivot
(
 sum([profile]) for [quarter]
 in
 ([1],[2],[3],[4])
)
as
s

注:使用pivot把一列拆成几列时 需要后面as取个别名 这是固定的格式 同时如 for前是必须使用聚合函数的

当然不使用pivot函数也可以得到相同效果 只是代码长切效率低 但容易理解

select id,[name],
'1'=(select sum([profile]) from test where id=a.id and quarter=1),
'2'=(select sum([profile]) from test where id=a.id and quarter=2),
'3'=(select sum([profile]) from test where id=a.id and quarter=3),
'4'=(select sum([profile]) from test where id=a.id and quarter=4)
from test as a
group by id,name

-----------------------------------------------------------------------------------------

unpivot函数 顾名思义 他就是把几列合并到1列中去

create table test1(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int)

insert into test1 values(1,'a',1000,2000,4000,5000)
insert into test1 values(2,'b',3000,3500,4200,5500)

select * from test1 --创建test1表

我们要把Q1 Q2 Q3 Q4合到1列 季度列中去 如效果:

使用unpivot可以很简单的实现

select id ,[name],[jidu],[xiaoshou] from test1
unpivot
(
 xiaoshou for jidu in
 ([q1],[q2],[q3],[q4])
)
as f

注:同样需要使用as取别名同样是固定的格式 unpivot函数中没有聚合函数 xiaoshou和jidu列都是原来没有的 jidu表由原来的Q1 Q2 Q3 Q4组成 

同样的不使用unpivot也可以实现以上的功能

select id,[name],
jidu='Q1',
xiaoshou=(select Q1 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q2',
xiaoshou=(select Q2 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q3',
xiaoshou=(select Q3 from test1 where id=a.id)
from test1 as a
union
select id,[name],
jidu='Q4',
xiaoshou=(select Q4 from test1 where id=a.id)
from test1 as a

最新文章

  1. 1.2.1 OC概述
  2. HiveQL 与 SQL的异同
  3. Cocos2D-X2.2.3学习笔记9(处理重力感应事件,移植到Android加入两次返回退出游戏效果)
  4. bzoj4038: 医疗援助
  5. C# 匿名方法和拉姆达表达式
  6. 【转载】十条jQuery代码片段助力Web开发效率提升
  7. github中删除项目
  8. shell编程基础(一): 基本变量和基本符号
  9. Laravel 5.2--git冲突error: Your local changes to the following files would be overwritten by merge:
  10. David Silver强化学习Lecture3:动态规划
  11. pychram 2018-01 安装pyQT5报错
  12. 远程批量查看windosws操作系统3389端口的开放情况
  13. information_schema系列十
  14. cocos2d-js 3.0 RC0 手动绑定 C++调用js,js调用C++ jsbinding
  15. 四大域对象,和jsp的九大隐式对象,已经el表达式的11个隐式对象
  16. hdu 1394 Minimum Inversion Number 逆序数/树状数组
  17. c#递归生成XML
  18. venus之hello world
  19. JAVA在语言级支持多线程
  20. WebViewJavascriptBridge详细使用 iOS与H5交互的方案

热门文章

  1. libSVM 简易使用手册
  2. 分层导航and隐藏导航
  3. yii Html中的a标签使用
  4. android 开发(百度地图)
  5. 在Javaweb中使用Scala
  6. 创建laravel项目时打开浏览器常见错误
  7. 颜色表及html代码
  8. oracle sql获取随机数
  9. Table Properties [AX 2012]
  10. HTML5与CSS3权威指南