sql列转行
来源:互联网 发布:安卓windows开始键图标 编辑:程序博客网 时间:2024/05/18 02:10
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[Source] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'语文',60)
INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'数学',70)
INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'英语',80)
INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'数学',75)
INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'语文',57)
INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'语文',80)
INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'英语',100)
Go
--交叉表语句的实现:
--用于:交叉表的列数是确定的
select name,sum(case subject when '数学' then source else 0 end) as '数学',
sum(case subject when '英语' then source else 0 end) as '英语',
sum(case subject when '语文' then source else 0 end) as '语文'
from test
group by name
--用于:交叉表的列数是不确定的
declare @sql varchar(8000)
set @sql = 'select name,'
select @sql = @sql + 'sum(case subject when '''+subject+'''
then source else 0 end) as '''+subject+''','
from (select distinct subject from test) as a
select @sql = left(@sql,len(@sql)-1) + ' from test group by name'
exec(@sql)
go
declare @sql varchar(8000)
set @sql = 'select id,'
select @sql = @sql + '(case subject when '''+subject+'''
then source else null end) as '''+subject+''','
from (select distinct subject from test) as a
select @sql = left(@sql,len(@sql)-1) + ' from test '
exec(@sql)
go
- sql列转行
- sql列转行
- 列转行SQL
- sql列转行
- sql列转行
- SQL 列转行
- SQL行转列 列转行
- sql 列转行
- SQL行转列,列转行
- sql 列转行
- sql 列转行
- SQL 列转行
- SQL列转行
- 列转行sql
- SQL 列转行
- SQL 列转行/行转列
- SQL 列转行
- sql server 列转行
- Struts2.0之类型转换篇
- C++代码规范之命名
- 如何有效结合IPD与CMM流程
- 经历了半年终于把海康的所有硬件搞进来了,再次证明了自己的观点。。。
- 深入探讨Iterator模式
- sql列转行
- sql优化之:深入浅出理解索引(系列一)(讲解非常透彻)
- Spring+Hibernate:使用注释和OSCache整合的简单实例
- sql优化之:深入浅出理解索引(系列二)(讲解非常透彻)
- sql优化之:改善SQL语句(系列三)
- sql 优化之:实现小数据量和海量数据的通用分页显示存储过程(系列四)
- 你一定要知道的71个做饭技巧
- sql 优化之:聚集索引的重要性和如何选择聚集索引(系列五)
- Cstring 和 chr * 的转换