-1

我有一个查询没有给我正确的结果。我试图在下表中获得一个城市的平均状态:

    SNO         SNAME                   STATUS      CITY
    s1          Smith                   20          London         
    s2          Jones                   10          Paris          
    s3          Blake                   30          Paris          
    s4          Clark                   20          London         
    s5          Adams                   30          Athens  

查询应返回所有城市的平均城市状态。我知道结果应该是 26.667,但事实上,我的 select 语句不起作用。这里是:

select avg(rs1.status) as average
from rs rs1, rs rs2
where rs1.city=rs2.city;

我得到的结果:

        AVERAGE
---------------
    21.11111111 

我忘了什么???还是我不需要自我加入?

创建表的代码:

create table rs
( sno    char(5)  not null,
  sname  char(20) not null,
  status smallint,
  city   char(15),
  primary key (sno)
);

insert into rs (sno, sname, status,city)
values('s1', 'Smith', 20, 'London');
insert into rs
values('s2', 'Jones', 10, 'Paris');
insert into rs
values('s3', 'Blake', 30, 'Paris');
insert into rs
values('s4', 'Clark', 20, 'London');
insert into rs
values('s5', 'Adams', 30, 'Athens');
4

1 回答 1

3

猜测最初的问题是“平均每个城市在所有城市中的最大(!)状态是多少?”:

SELECT AVG(m.mstatus)
FROM (SELECT MAX(status) AS mstatus
      FROM rs
      GROUP BY city) AS m

给定您的示例数据,结果是26.66666...

于 2013-09-10T18:23:05.427 回答