所以我有以下查询..
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
我该怎么做?感谢。
答案 0 :(得分: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
答案 1 :(得分: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子句中)。