日期:2014-05-19  浏览次数:20453 次

初学者问个最基础的关联查询问题,在线等待,谢谢!
表一
ID         姓名         班级
1           甲             3
2           乙             2
3           丙             5
4           丁             3

表二
ID         语文         数学         英语         政治
1             81             99             63             76
2             34             78             98             90
3             77             45             66             78
4             85             90             88             67

希望得到的结果是
姓名         平均成绩         总成绩         班级
***               ***                   ***             *

按照平均成绩从高到低进行排列。

------解决方案--------------------
select b.姓名,
(语文+数学+英语+政治)/4 as 平均成绩,
(语文+数学+英语+政治) as 总成绩,
b.班级
from 表2 as a left join 表1 on a.ID = b.ID
order by 2 DESC
------解决方案--------------------
if object_id( 't1 ')> 0 drop table t1
create table t1(ID int,[语文] int,[数学] int,[英语] int,[政治] int)
insert into t1
select 1, 81, 99, 63, 76
union all
select 2, 34, 78, 98, 90
union all
select 3, 77, 45, 66, 78
union all
select 4, 85, 90, 88, 67

if object_id( 't2 ')> 0 drop table t2

create table t2(ID int,[姓名] varchar(20),[班级] int)

insert into t2
select 1, '甲 ',3
union all
select 2, '乙 ',2
union all
select 3, '丙 ',5
union all
select 4, '丁 ',3

select t1.ID,(t1.[语文]+t1.[数学]+t1.[英语]+t1.[政治])/4 as 平均分,
t1.[语文]+t1.[数学]+t1.[英语]+t1.[政治] as 总分,
t2.[班级]
from t1
left join t2 on t1.ID=t2.ID
order by t1.平均分


/*
ID 平均分 总分 班级
--------------------------------
3 66 266 5
2 75 300 2
1 79 319 3
4 82 330 3
*/
------解决方案--------------------
--建立环境
create table Tb1(id int,姓名 varchar(10),班级 int)

insert Tb1 select 1, '甲 ',3
union all select 2, '乙 ',2
union all select 3, '丙 ',5
union all select 4, '丁 ',3


create table Tb2(id int,语文 int,数学 int,英语 int,政治 int)

insert Tb2 select 1,81,99,63,76
union all select 2,34,78,98,90
union all select 3,77,45,66,78
union all select 4,85,90,88,67

--查询语句

select
tb1.姓名,(语文+数学+英语+政治)/4 as 平均成绩,(语文+数学+英语+政治) as 总成绩,tb1.班级
from tb1
left joi