sql列转行
来源:互联网 发布:哈登数据 编辑:程序博客网 时间:2024/05/12 01:58
[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 列转行
- Sql server 2005带来的分页便利
- js脚本使用大全
- 工作中经常用的好工具
- [转载]国外专家:重回学校学IT,你还该学哪些?
- (转)Spring 2.0的新特性和应用实践
- sql列转行
- C#调用存储过程简单完整例子
- 制作Javascript弹出窗口技巧九则
- 测试测试。。。。
- 初学者SQL语句介绍
- 初学者SQL语句介绍
- 文档对象模型(DOM)
- ASP.NET中如何防范SQL注入式攻击
- 下面介绍如何制作这样的报表