Never give up - LEO

人 只有在合适的地方 才能体现出最大的价值
  博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

SQL语句查询--Student,Project,Actor

Posted on 2007-01-19 16:31  lizhiwen  阅读(245)  评论(0编辑  收藏  举报

/*
create table A_Student(ID int,StudentName nvarchar(20),SpecialtyID int)
create table A_Project(ID int,ProjectName nvarchar(20),Reward money)
create table A_Actor(ID int,StudentID int,ProjectID int,WorkTime decimal)
*/
--select * from A_Student
/*
1 张三 10
2 李四 11
3 王五 12
4 赵六 13
5 李三 11
6 张四 10
*/
--select * from A_Project
/*
100 项目一 20.0000
101 项目二 50.0000
102 项目三 40.0000
*/
--select * from A_Actor
/*
1 1 100 10
2 2 100 5
3 3 101 6
4 4 101 10
5 5 102 20
6 6 101 30
7 6 102 10
8 3 102 5
*/
select distinct * from A_Actor A,A_Actor B
 where A.StudentID = B.StudentID
/*
1 1 100 10 1 1 100 10
2 2 100 5 2 2 100 5
3 3 101 6 3 3 101 6
3 3 101 6 8 3 102 5
4 4 101 10 4 4 101 10
5 5 102 20 5 5 102 20
6 6 101 30 6 6 101 30
6 6 101 30 7 6 102 10
7 6 102 10 6 6 101 30
7 6 102 10 7 6 102 10
8 3 102 5 3 3 101 6
8 3 102 5 8 3 102 5
可以发现这个语句查询出来的结果,凡是做过两个及以上项目的纪录都会大于一条,这也是inner join的连接结果
*/
select distinct A.StudentID from A_Actor A,A_Actor B
 where A.StudentID = B.StudentID and A.ProjectID <> B.ProjectID
/*
3
6
当加上‘and A.ProjectID <> B.ProjectID’之后只有一个项目的便排除了,只剩下两个及以上的学员编号
*/

--查询每个专业的薪酬总额,专业ID
select * from A_Actor A
 left join A_Project P on A.ProjectID = P.ID
 left join A_Student S on A.StudentID = S.ID
/*
1 1 100 10 100 项目一 20.0000 1 张三 10
2 2 100 5 100 项目一 20.0000 2 李四 11
3 3 101 6 101 项目二 50.0000 3 王五 12
4 4 101 10 101 项目二 50.0000 4 赵六 13
5 5 102 20 102 项目三 40.0000 5 李三 11
6 6 101 30 101 项目二 50.0000 6 张四 10
7 6 102 10 102 项目三 40.0000 6 张四 10
8 3 102 5 102 项目三 40.0000 3 王五 12
上句查询把需要计算的几个字段组合到一个表里面,下面的语句就好做了
*/

select S.SpecialtyID,sum(P.Reward*A.WorkTime) as 薪酬总额 from A_Actor A
 left join A_Project P on A.ProjectID = P.ID
 left join A_Student S on A.StudentID = S.ID
 group by S.SpecialtyID
/*
10 2100.0000
11 900.0000
12 500.0000
13 500.0000
*/