Chinaunix首页 | 论坛 | 博客
  • 博客访问: 486305
  • 博文数量: 105
  • 博客积分: 2922
  • 博客等级: 少校
  • 技术积分: 1113
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-02 16:30
文章分类

全部博文(105)

文章存档

2018年(1)

2016年(2)

2015年(3)

2014年(6)

2013年(21)

2012年(10)

2011年(8)

2010年(7)

2009年(31)

2008年(16)

我的朋友

分类: Oracle

2009-09-06 11:02:20

--行列互转
/******************************************************************************************************************************************************
以学生成绩为例子,比较形象易懂

整理人:中国风(Roy)

日期:2008.06.06
******************************************************************************************************************************************************/

--1、行互列
--> --> (Roy)生成測試數據

if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
--2000方法:
动态:

declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+' from Class group by [Student]')


生成静态:

select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end)
from
Class
group by [Student]

GO
动态:

declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')

生成静态:
select *
from
Class
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b

生成格式:
/*
Student 数学 物理 英语 语文
------- ----------- ----------- ----------- ---
阅读(1092) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-09-17 16:26:24

推荐视频会议、视频直播、视频面试、视频招聘、视频监控等视频系统: http://www.eyesom.com/products/var.htm