按日期分组和版本查询错误的最大值

时间:2017-09-25 17:11:56

标签: mysql sql database

这是我当前的SQL查询:

SELECT `room_id`, `target_date`, `rate_per_room`, `max_room`, MAX(`version`)
    FROM `t0311_room_rate`
        WHERE `room_id` = ?
           AND `target_date` >= ?
           AND `target_date` is not null 
           GROUP BY `target_date`
           ORDER BY `target_date`

这些是我的样本数据

enter image description here

如果我查询target_date> =今天我应该得到三条记录,其中是,它确实如此。 但是,版本和rate_per_room不符合。 例如版本12,我应该得到195,但我得到190.

我的查询中是否有任何遗漏?

谢谢

1 个答案:

答案 0 :(得分:1)

听起来你想要MAX(rate_per_room)。您还应该将其他非汇总列添加到GROUP BY。大多数RDBMS会让你这样做,但MySQL是'特殊'。

SELECT `room_id`, `target_date`, MAX(`rate_per_room`), `max_room`, MAX(`version`)
FROM `t0311_room_rate`
WHERE `room_id` = ?
AND `target_date` >= ?
AND `target_date` is not null 
GROUP BY `room_id`, `target_date`, `max_room`
ORDER BY `target_date`

修改

由于MAX(version)并不总是与MAX(rate_per_room)匹配,因此您应首先获取MAX(version),然后将JOIN返回到表中以获取其余数据:

SELECT b.room_id, b.target_date, b.rate_per_room, b.max_room, a.version
FROM (SELECT room_id, MAX(Version) as version
      FROM t0311_room_rate
      GROUP BY room_id) a
INNER JOIN t0311_room_rate b on a.room_id = b.room_id
                            and a.version = b.version
--Add filters as desired
ORDER BY target_date