无法正确GROUP BY(SQL)

时间:2012-10-17 11:20:34

标签: sql oracle

我有一个SQL查询,当前显示表HOTEL中预订了260美元到350美元之间酒店的所有人。我正在使用ORACLE

SELECT guest.guest_name "GUEST NAME", 
       Count(guest.guest_no), 
       guest.guest_no   "GUEST           NUMBER", 
       room.r_price     "ROOM PRICE" 
FROM   room, 
       guest, 
       booking 
WHERE  r_price >= 260 
       AND r_price <= 350 
       AND guest.guest_no = booking.guest_no 
GROUP  BY guest.guest_no, 
       guest.guest_name, 
       room.room_price 
ORDER  BY guest.guest_name; 

我认为我可以只通过GUEST.GUEST_NAME进行分组(因此它会将所有计数放在一个名称下,而不是将客户名称加倍)。

编辑:查询的当前结果如下所示:

    GUEST NAME    COUNT   GUEST_NO R_PRICE
    Jenny Freeman   2   G003    260
    Jenny Freeman   2   G003    295
    Jenny Freeman   2   G003    310
    Martin Ferguson 3   G006    260
    Martin Ferguson 3   G006    295
    Martin Ferguson 3   G006    310
    Paul Happy  3   G002    260
    Paul Happy  3   G002    295
    Paul Happy  3   G002    310
    Steve Kirkwood  3   G005    260
    Steve Kirkwood  3   G005    295
    Steve Kirkwood  3   G005    310
    Tina Duncan 2   G001    260
    Tina Duncan 2   G001    295
    Tina Duncan 2   G001    310
    Vanessa Horton  1   G007    260
    Vanessa Horton  1   G007    295
    Vanessa Horton  1   G007    310

但是我期待这样的事情:

    GUEST NAME    COUNT   GUEST_NO R_PRICE
    Jenny Freeman   6   G003    260
    Martin Ferguson 9   G006    310
    Paul Happy  9   G002    310
    Steve Kirkwood  9   G005    260
    Tina Duncan 6   G001    310
    Vanessa Horton  3   G007    260

3 个答案:

答案 0 :(得分:1)

好吧,我认为你只需要改变一组声明休息看起来对我好。只是不要在Group By声明中包含房间价格,我认为如果我的问题正确,那就会给你带来问题......

 GROUP BY GUEST.GUEST_NO,
          GUEST.GUEST_NAME

 MAX(R_PRICE) 

答案 1 :(得分:0)

您可能忘记通过ROOM_NO(或其他领域)的预订加入ROOM吗? 我已经从分组中删除了房间价格,现在查询将返回唯一的客人和他们预订的房间数量,以及给定范围内的价格,以及每位客人的最高价格。

SELECT
    GUEST.GUEST_NAME "GUEST NAME",
    GUEST.GUEST_NO "GUEST NUMBER",
    COUNT(*) "CNT",
    MAX(R.R_PRICE) "ROOM PRICE"
FROM BOOKING B
    inner join ROOM R on R.ROOM_NO = B.ROOM_NO
    inner join GUEST G on G.GUEST_NO  = B.GUEST_NO
WHERE R.R_PRICE>=260 and R.R_PRICE<=350
GROUP BY G.GUEST_NO, G.GUEST_NAME
ORDER BY G.GUEST_NAME;

答案 2 :(得分:-2)

您可以尝试以下sql查询:

SELECT GUEST.GUEST_NAME "GUEST NAME", COUNT(GUEST.GUEST_NO), GUEST.GUEST_NO "GUEST NUMBER", ROOM.R_PRICE "ROOM PRICE"
FROM ROOM, GUEST,BOOKING
WHERE ROOM.R_PRICE>=260
AND ROOM.R_PRICE<=350
AND GUEST.GUEST_NO = BOOKING.GUEST_NO
GROUP BY GUEST.GUEST_NAME
ORDER BY GUEST.GUEST_NAME;