SQL 行列转换
来源:互联网 发布:数据库的特点是什么 编辑:程序博客网 时间:2024/05/16 16:41
SQL行列转换
以下在达梦数据库6.0中测试通过
wisgood原创
例子中用到的两个表
课程表course
Course(C#,Cname,T#) --C# --课程编号,Cname课程名称,T#教师编号
测试表 test
Test(C#,Property,Value) --C# --课程编号,Property属性,Value值
create table Course(C# varchar(10),Cname varchar(10),T# varchar(10))
insert into Course values('01' , '语文' , '02')
insert into Course values('02' , '数学' , '01')
insert into Course values('03' , '英语' , '03')
1:从行转换成列
select c#,'cname'as property,cname
from course
union
select c#,'t#',t#
from course
为了便于从列转换成行,我们把得到的数据存入test表中
insertinto test(
select c#,'cname'as property,cname
from course
union
select c#,'t#',t#
from course
)
Test表中数据变为
2:从列转换成行
即把test表转换成course表的形式
第一种方法:通过连接的形式
select temp.c#,a.valueas cname,b.valueas t#
from(selectdistinct c#from test) temp
leftjoin test aon(temp.c#=a.c#and a.property='cname')
leftjoin test bon(temp.c#=b.c#and b.property='t#')
第二种方法:通过case语句
select test.c#,
casewhen test.property='cname'then test.valueelsenullend as [cname],
casewhen test.property='t#'then test.valueelsenullend as [t#]
from (selectdistinct c#from test) temp
join teston(test.c#=temp.c#)
此时得到的表如下,不符合条件,需要进一步处理
select test.c#,
max(casewhen test.property='cname'then test.valueelsenullend)as [cname],
max(casewhen test.property='t#'then test.valueelsenullend )as [t#]
from (selectdistinct c#from test) temp
join test on(test.c#=temp.c#)
groupby test.c#
得到满足条件的行
- SQL进行行列转换
- SQL的行列转换
- sql 行列转换
- SQL 行列转换查询
- SQL 行列转换查询
- SQL行列转换实战
- SQL 行列转换
- SQL行列转换实战
- sql server 行列转换
- SQL行列转换
- sql server 行列转换
- 经典SQL----行列转换
- SQL Server 行列转换
- 经典SQL行列转换
- sql 行列转换
- SQL行列转换
- 行列转换的SQL
- SQL行列转换
- 如何打开Oracle 10g的企业管理器(Enterprise Manager)和http://localhost:1158/em出现问题。
- USACO 4.3.2 the primes
- JS技巧:JS对select动态添加options操作[IE&FireFox兼容]
- Oracle管理员认证方式
- Zoj 2956 Another Horizontally Visible Segments
- SQL 行列转换
- .Net Framework内存管理简介
- zoj 1465 || poj 1113 Wall
- Dojo mobile TweetView 系列教程之一 —— dojox.mobile入门
- 网络负载平衡改造(续2)
- 从头开始编写操作系统(1) 第0章:序章
- 使用Varnish对大型内网进行缓存
- BizTalk请求JAVA的Web Service报错
- Asp.net网站有关数据库怎么设置啊