首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求SQL 语句 如何搞这个例子

2012-07-16 
求SQL 语句 怎么搞这个例子我就不上图了 。。如题:SQL 表本意是这样的id nametypefshu1张三语文902张三数学8

求SQL 语句 怎么搞这个例子
我就不上图了 。。

如题:
SQL 表本意是这样的
id name type fshu
1 张三 语文 90
2 张三 数学 80
3 张三 英语 86
3 李四 数学 78
3 李四 英语 89
3 李四 英语 98
3 王五 语文 90
3 王五 数学 87
3 王五 英语 80

现在要改成:

1 张三 语文 90 数学 80 英语 86
2 李四 语文 78 数学 89 英语 98
3 王五 语文 90 数学 87 英语 80

本人初学者。。让前辈们见笑了 。 谢谢各位了~

[解决办法]

SQL code
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')BEGIN    DROP TABLE tbaENDGOCREATE TABLE tba(    id INT,    name VARCHAR(100),    type VARCHAR(100),    fshu INT)GOINSERT INTO tbaSELECT 1, '张三', '语文', 90 UNIONSELECT 2, '张三', '数学', 80 UNIONSELECT 3, '张三', '英语' ,86 UNIONSELECT 3, '李四', '数学' ,78 UNIONSELECT 3, '李四', '英语', 89 UNIONSELECT 3, '李四', '语文', 98 UNIONSELECT 3, '王五', '语文', 90 UNIONSELECT 3, '王五', '数学', 87 UNIONSELECT 3, '王五', '英语', 80GOdeclare @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) texec ('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
[解决办法]
SQL code
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([id] int,[name] varchar(4),[type] varchar(4),[fshu] int)insert [tb]select 1,'张三','语文',90 union allselect 1,'张三','数学',80 union allselect 1,'张三','英语',86 union allselect 2,'李四','语文',78 union allselect 2,'李四','数学',89 union allselect 2,'李四','英语',98 union allselect 3,'王五','语文',90 union allselect 3,'王五','数学',87 union allselect 3,'王五','英语',80goselect a.id,a.name,a.type,a.fshu,b.type,b.fshu,c.type,c.fshufrom tb ajoin 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          英语   862           李四   语文   78          数学   89          英语   983           王五   语文   90          数学   87          英语   80(3 行受影响)**/ 

热点排行