0

所以我有以下查询..

select rooms.id room_id, rooms.cnt, booked_dates.cnt, sum(booked_dates.cnt) 
from rooms 
LEFT JOIN booked_dates 
       on rooms.id = booked_dates.rid and 
          (booked_dates.start between '2013-05-06' and '2013-05-09')
where rooms.ht = 4 and rooms.id = 138 
group by booked_dates.start

它返回以下结果..

在此处输入图像描述

现在我需要按 对结果进行分组room_id并获取列max中的数字sum(booked_dates.cnt)。因此,对于示例,它将是:

138 | 20 | 4 | 12

我该怎么做?谢谢。

4

2 回答 2

1
SELECT  rooms.id room_id, rooms.cnt, booked_dates.cnt, SUM(booked_dates.cnt) AS booked_sum
FROM    rooms 
LEFT JOIN
        booked_dates 
ON      rooms.id = booked_dates.rid
        AND (booked_dates.start between '2013-05-06' and '2013-05-09')
WHERE   rooms.ht = 4
        AND rooms.id = 138 
GROUP BY
        booked_dates.start
ORDER BY
        booked_sum DESC
LIMIT   1
于 2013-05-05T19:49:55.723 回答
0

添加一个 max() 列:

select
    rooms.id room_id,
    rooms.cnt,
    booked_dates.cnt, 
    max(booked_dates.cnt) as max ,
    sum(booked_dates.cnt) as sum
from rooms 
LEFT JOIN booked_dates 
   on rooms.id = booked_dates.rid and 
      (booked_dates.start between '2013-05-06' and '2013-05-09')
where rooms.ht = 4 and rooms.id = 138 
group by 1, 2, 3

您的 group by 子句中有一个错误 - 此查询也修复了该问题(请注意,您可以在 group by 子句中通过它们的位置而不是它们的表达式来引用列)。

于 2013-05-05T19:41:19.033 回答