求一个带group by的多表连查的sql语句

来源:百度知道 编辑:UC知道 时间:2024/06/04 20:17:44
table1:(pID可重复)
pID pScore
1 20
1 40
1 51
2 32
3 65
3 80

table2:(pID唯一索引)
pID pType orgCode
1 H1 11
2 H2 22
3 H3 33

table3:(orgCode唯一索引)
orgCode orgName
11 MM
22 NN
33 KK

我想实现的查询功能:
table1表相同PID的pScore的平均分数,相同PID的个数pCount, 以及关联的table2,table3的对应pID的信息
如上结果应该为:
pID pScore pCount pType orgName
1 37 3 H1 MM
2 32 1 H2 NN
3 48.3 2 H3 KK

select avg(pScore),count(*) from table1 group by pID 可以求table1平均分和个数,
但怎样通过pID把table2,table3关联起来呢?望高手帮写个sql语句。

SELECT a.pid,a.pscore,a.count,b.ptype,c.orgname
FROM (select a.pid,avg(a.pscore)as pscore,count(a.pid)as count
from table11 a
group by a.pid ) a, table12 b,table13 c
where a.pid = b.pid and b.orgcode = c.orgcode
你结果的第三行是65和80的平均值吗
oracle的,测试ok

学习,答案都一样
而且,你的3 KK 48.3是怎么算出来的,奇怪

select table4.pID,table4.avgscore,table4.countnum,table2.pType ,table3.orgName from table2,table3,(select pID,avg(pScore) avgscore,count(*) countnum from table1 group by pID) table4 where table2.pID=table4.pID and table3.orgCode=table2.orgCode

oracle下,没有测试

Oracle 下很简单
但是好久没用sql server 勒
下面的语句不知道行不
希望你试过之后通知我
谢谢

select a.pid , a.avg_pscore as pScore, a.tot_count as pCount , b.pType , c.orgName
(
select pid , avg(pScore) as avg_pscore,count(*) as tot_count
from table1
group by pID
) a ,
table2 b ,
table3 c
where a.pid = b.pid
and b.orgCode = c.orgC