sql语句实现行转列的3种方法实例
前言
一般在做数据统计的时候会用到行转列,假如要统计学生的成绩,数据库里查询出来的会是这样的,但这并不能达到想要的效果,所以要在查询的时候做一下处理,下面话不多说了,来一起看看详细的介绍。
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
create table testtable(
[id] [int] identity(1,1) not null,
[username] [nvarchar](50) null,
[subject] [nvarchar](50) null,
[source] [numeric](18, 0) null
) on [primary]
go
insert into testtable ([username],[subject],[source])
select n'张三',n'语文',60 union all
select n'李四',n'数学',70 union all
select n'王五',n'英语',80 union all
select n'王五',n'数学',75 union all
select n'王五',n'语文',57 union all
select n'李四',n'语文',80 union all
select n'张三',n'英语',100
go
|
这里我用了三种方法来实现行转列第一种:静态行转列
?
|
1
2
3
|
select username 姓名,
sum(case subject when '语文' then source else 0 end) 语文,sum(case subject when '数学' then source else 0 end) 数学,
sum(case subject when '英语' then source else 0 end) 英语 from testtable group by username
|
用povit行转列
?
|
1
2
3
|
select * from
(select username,subject,source from testtable) testpivot(sum(source) for subject in(语文,数学,英语)
) pvt
|
用存储过程行转列
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
alter proc pro_test
@userimages varchar(200),
@subject varchar(20),
@subject1 varchar(200),
@tablename varchar(50)
as
declare @sql varchar(max)='select * from (select '+@userimages+' from'+@tablename+') tab
pivot
(
sum('+@subject+') for subject('+@subject1+')
) pvt'
exec (@sql)
go
exec pro_test 'username,subject,source',
'testtable',
'subject',
'语文,数学,英语'
|
它们的效果都是这样的

以上三种方式实现行转列,我们可以根据自己的需求采用不同的方法
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
文章版权声明:除非注明,否则均为奥多云原创文章,转载或复制请以超链接形式并注明出处。




还没有评论,来说两句吧...