日期:2014-05-18 浏览次数:20658 次
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')
BEGIN
DROP TABLE tba
END
GO
CREATE TABLE tba
(
id INT,
name VARCHAR(100),
type VARCHAR(100),
fshu INT
)
GO
INSERT INTO tba
SELECT 1, '张三', '语文', 90 UNION
SELECT 2, '张三', '数学', 80 UNION
SELECT 3, '张三', '英语' ,86 UNION
SELECT 3, '李四', '数学' ,78 UNION
SELECT 3, '李四', '英语', 89 UNION
SELECT 3, '李四', '语文', 98 UNION
SELECT 3, '王五', '语文', 90 UNION
SELECT 3, '王五', '数学', 87 UNION
SELECT 3, '王五', '英语', 80
GO
declare @sql varchar(max)
select @sql=isnull(@sql+',','')
+'max(case when rn='+ltrim(rn)+' then type end) as [科目],'
+'max(case when rn='+ltrim(rn)+' then fshu end) as [分数]'
from
(select distinct rn=row_number() over(partition by name order by type) from tba) t
exec ('select name,'
+@sql
+' from (select *,rn=row_number() over(partition by name order by type) from tba) t group by name'
)
name 科目 分数 科目 分数 科目 分数
李四 数学 78 英语 89 语文 98
王五 数学 87 英语 80 语文 90
张三 数学 80 英语 86 语文 90
------解决方案--------------------
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[name] varchar(4),[type] varchar(4),[fshu] int)
insert [tb]
select 1,'张三','语文',90 union all
select 1,'张三','数学',80 union all
select 1,'张三','英语',86 union all
select 2,'李四','语文',78 union all
select 2,'李四','数学',89 union all
select 2,'李四','英语',98 union all
select 3,'王五','语文',90 union all
select 3,'王五','数学',87 union all
select 3,'王五','英语',80
go
select a.id,a.name,a.type,a.fshu,b.type,b.fshu,c.type,c.fshu
from tb a
join tb b on a.id=b.id and b.type='数学'
join tb c on a.id=c.id and c.type='英语'
where a.type='语文'
/**
id name type fshu type fshu type fshu
----------- ---- ---- ----------- ---- ----------- ---- -----------
1 张三 语文 90 数学 80 英语 86
2 李四 语文 78 数学 89 英语 98
3 王五 语文 90 数学 87 英语 80
(3 行受影响)
**/