SQL查询查找平均值

时间:2016-01-30 19:15:33

标签: mysql sql

我创建了三个表

CREATE TABLE guest(

name varchar(100),
ranking int,
PRIMARY KEY (name)
);

CREATE TABLE room(

 roomname varchar(100),
 wallcolor varchar(100),
 rating int,
 PRIMARY KEY(roomnane)
 );

 CREATE TABLE reservation(

 name varchar(100),
 roomname varchar(100),
 day varchar(100),
 moveinday int,
 moveoutday int,
 PRIMARY KEY(roomname, day, start, finish),
  FOREIGN KEY(roomname) REFERENCES room(roomname),
  FOREIGN KEY(name) REFERENCES guest(name)
 );

我正在尝试创建两个查询

  1. 对于每个预订的房间,列出客人的平均排名 保留那个房间。我无法列出每个房间的平均值。这是我试过的

    select reservation.roomname, AVG(guest.ranking)
    from reservation, room, guest
     where reservation.roomname == room.roomname AND reservation.name = guest.name
    
  2. 这不能提供所需的结果。我该如何修复我的查询?

    1. 查询以确认房间没有冲突的预订。 (同一个房间不能为多人搬家和搬家日保留。我不知道如何开始这个

3 个答案:

答案 0 :(得分:2)

别忘了GROUP BY

SELECT reservation.roomname, AVG(guest.ranking)
FROM reservation, room, guest
WHERE reservation.roomname = room.roomname 
AND reservation.name = guest.name
GROUP BY reservation.roomname

答案 1 :(得分:1)

您应该学会使用正确的join语法和表别名。

select r.roomname, AVG(g.ranking)
from room r join
     guest g
     on r.name = g.name
group by r.roomname;

此外,实际上并不需要room表。

答案 2 :(得分:1)

关于你的第二个问题,基本应该是这样一个联接:

select room.roomname 
from room
join reservation r1 on room.roomname = r1.roomname 
join reservation r2 on room.roomname = r2.roomname 

然后where子句是复杂的部分:

where (r1.moveinday < r2.moveinday and r1.moveoutday > r2.moveoutday)
or (r1.moveinday < r2.moveinday and r1.moveoutday > r2.moveinday)
or (r1.moveinday < r2.moveoutday and r1.moveoutday > r2.moveoutday)

第一种情况:r1完全包含r2。

第二种情况:r1与r2中的移动重叠

第三种情况:r1与r2的移出日重叠

你可能想要使用&lt; =,&gt; =,取决于你如何考虑这种情况。如果你想使用&lt; =,&gt; =(而不是&lt;。&gt;),我建议你为每个预订添加一个唯一的ID,因为你必须添加到where子句中,例如 r1.ID&lt;&gt; r2.ID