SQL在给定小时内获得最高金额的记录

时间:2014-07-11 18:27:09

标签: mysql sql greatest-n-per-group

我想在给定时间内获得最高amount的记录。

DB中的数据:

id | date                | amount 
–––––––––––––––––––––––––––––––––
1  | 2014-07-11 18:10:00 | 10
2  | 2014-07-11 18:20:00 | 20
3  | 2014-07-11 18:30:00 | 100
4  | 2014-07-11 18:40:00 | 10
5  | 2014-07-11 19:10:00 | 50
6  | 2014-07-11 19:20:00 | 60

期望的结果:

id | date                | amount 
---------------------------------
3  | 2014-07-11 18:30:00 | 100
6  | 2014-07-11 19:20:00 | 60

4 个答案:

答案 0 :(得分:4)

如果我正确理解您的问题,您可以使用最大聚合将表格连接回自身,按小时和日期分组:

select d.*
from data d
  join (select max(amount) maxamount, hour(date) datehour, date(date) date
        from data
        group by hour(date), date(date)
        ) d2 on d.amount = d2.maxamount 
          and hour(d.date) = d2.datehour
          and date(d.date) = d2.date

答案 1 :(得分:2)

这样的事情? - 假设表名是交易

SELECT
    *
FROM
(
    SELECT 
        id, date, amount
    FROM transactions
    ORDER BY amount DESC
) AS t
GROUP BY HOUR(date) , DATE(date);

WORKING FIDDLE

答案 2 :(得分:2)

您也可以使用not exists方法解决此问题:

select d.*
from data d
where not exists (select 1
                  from data d2
                  where date(d2.date) = date(d.date) and
                        hour(d2.date) = hour(d.date) and
                        d2.amount > d.amount
                 );

这只是一种替代解决方案。有时not exists比使用group by的{​​{1}}快,但在这种情况下可能不会。

答案 3 :(得分:1)

这应该足够了:

SELECT      Id, 
            Dating,
            Amount
FROM        Tab
WHERE       Amount IN (SELECT       MAX(Amount) AS 'Maximum Amount'
                       FROM         Tab
                       GROUP BY     HOUR(Dating), DATE(Dating))

你可以在这里看到 - > SQL Fiddle Demo

希望这有帮助!!!