读书人

菜鸟问个最基础的关联查询有关问题待

发布时间: 2012-03-01 10:25:46 作者: rapoo

初学者问个最基础的关联查询问题,在线等待,谢谢!
表一
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 平均分 总分 班级
--------------------------------
3662665
2753002
1793193
4823303
*/
[解决办法]
--建立环境
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 join tb2 on tb1.ID = tb2.ID


order by 总成绩 DESC

--(所影响的行数为 4 行)

读书人网 >SQL Server

热点推荐