按日期从表顺序中选择行,并将类似日期限制为1

时间:2015-07-28 05:37:05

标签: mysql sql

我有一张表

id | name    | datetime            | percentage
-----------------------------------------------
1  | amit    | 2015-06-20 18:30:00 | 60
2  | pavan   | 2015-06-20 18:30:00 | 60
3  | vineet  | 2015-06-20 18:30:00 | 50
4  | pavan   | 2015-06-21 19:30:00 | 70
5  | vineet  | 2015-06-21 19:30:00 | 70
6  | amit    | 2015-06-21 18:30:00 | 60
7  | vineet  | 2015-06-19 18:30:00 | 80

我想选择行并按日期时间和百分比排序,并将它们限制为1行。我不想要多个日期

    id | name    | datetime            | percentage
    -----------------------------------------------
    7  | vineet  | 2015-06-19 18:30:00 | 80
    1  | amit    | 2015-06-20 18:30:00 | 60   
    6  | amit    | 2015-06-21 18:30:00 | 60    
    4  | pavan   | 2015-06-21 19:30:00 | 70

2 个答案:

答案 0 :(得分:2)

尝试此查询

select a.* from tablename a
join (select min(c.id) as id ,c.datetime
      from tablname c
      join(
         select max(percentage) as percentage, datetime
      from tablname
        group by datetime
        )  d on c.datetime=d.datetiem and c.percentage=d.percentage
      group by c.datetime) b on a.id=b.id
order by a.datetime,a.percentage

答案 1 :(得分:0)

尝试此查询

SELECT * 
    FROM mytable 
    WHERE id IN (SELECT MAX(id) 
                FROM mytable 
                GROUP BY datetime)
    ORDER BY datetime