`
wisgood
  • 浏览: 14620 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

sql 行列转换

阅读更多
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表中
insert into test(
select c#,'cname' as property ,cname
from course
union
select c#,'t#' ,t#
from course
)
Test表中数据变为





2: 从列转换成行
即把test表转换成course表的形式
第一种方法:通过连接的形式
select temp.c#,a.value as cname,b.value as t#
from (select distinct c# from test ) temp
left join test a on (temp.c#=a.c# and a.property='cname')
left join test b on (temp.c#=b.c# and b.property='t#')
第二种方法:通过case语句
select test.c#,
case when test.property='cname' then test.value else null end  as [cname],
case when test.property='t#' then test.value else null end  as [t#]
from  (select distinct c# from test ) temp
join test on (test.c#=temp.c#)

此时得到的表如下,不符合条件,需要进一步处理







select test.c#,
max(case when test.property='cname' then test.value else null end ) as [cname],
max(case when test.property='t#' then test.value else null end  )as [t#]
from  (select distinct c# from test ) temp
join test on (test.c#=temp.c#)
group by test.c#
得到满足条件的行




  • 大小: 13.6 KB
  • 大小: 18.7 KB
  • 大小: 18.7 KB
  • 大小: 20.3 KB
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics