【问题标题】:How can I select the record with the latest date in each group如何选择每组中日期最晚的记录
【发布时间】:2013-07-11 23:29:17
【问题描述】:

我有一张桌子,我们称之为桌子: table(id: integer, pid: integer, end: datetime)

具有以下数据:

table:
id    pid   end
1     1     1
2     1     2
3     1     3
4     2     11
5     2     12
6     2     13
7     3     21
8     3     22
9     3     23
10    4     31
11    4     32
12    4     33

我需要做的是选择记录的 id,按 pid 分组,具有最高的结束值。我的输出(作为 ActiveRecord::Relation)应该如下:

[#<Table id: 3, pid: 1, end: 3>,
 #<Table id: 6, pid: 2, end: 13>,
 #<Table id: 9, pid: 3, end: 23>,
 #<Table id: 12, pid: 4, end: 33>]

您能给我的任何方向都非常感谢。

【问题讨论】:

    标签: mysql ruby-on-rails-3 activerecord arel


    【解决方案1】:

    这应该可以完成工作

        select `id` , `pid` , `end` from table1
        where `end` in (select max(`end`) from table1)
    

    DEMO HERE

    由于您的建议,请尝试此编辑

         select `id` , `pid` , `end` from 
        ( select max(id) id ,`pid` ,max(`end`) as `end` from table1 group by `pid`)t
    

    DEMO HERE

    【讨论】:

    • 我认为这可行,但我注意到我的问题的表述存在问题。在实践中,每组的最终值不会相同。我将编辑我的问题以解决此问题。谢谢!
    【解决方案2】:

    即使您的最大 end 并不总是对应于最大 id 并且如果有多个 id 具有相同的最大 end,这也应该有效。

    SELECT t1.id, t1.pid, t1.end FROM Table1 t1
    JOIN 
    (SELECT pid AS 'pid2', MAX(end) AS 'end2' FROM Table1 GROUP BY pid) t2
    ON t2.pid2=t1.pid AND t2.end2=t1.end
    #GROUP BY t1.pid  #in case there are several records with same 'pid' and 'end' and you want to select any one of those
    

    SQL Fiddle

    【讨论】:

      【解决方案3】:
      select * from
      (select id,pid,end from Table1 order by pid asc, end desc) abc
      group by pid;
      

      fiddle

      【讨论】:

        猜你喜欢
        • 2020-08-22
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多