【问题标题】:How to get the second last record per group? [duplicate]如何获得每组倒数第二个记录? [复制]
【发布时间】:2018-05-04 21:33:16
【问题描述】:

我有一个名为 DemoTable 的表,其中包含一些字段,例如 com_nameupdated_datedemo_var,我查询过就像

select * from DemoTable where demo_var=100;

例如,这里我有 1000 条记录。在这 1000 条记录中,我想根据 updated_date

查询以获取 com_name 的最后更新行

我的桌子看起来像

id   demo_var   com_name   updated_date

1     100         XYZ         2017-11-10

2     100         XYZ         2017-11-09

3     100         ABC         2017-10-10

4     100         ABC         2017-10-11

5     150         AJD          2017-11-11

首先,我想知道 demo_var=100 的位置,并获取在更新之前最后的不同 com_name。

比如喜欢

2     100         XYZ         2017-11-09

3     100         ABC         2017-10-10

我想要获取这两条记录。

【问题讨论】:

标签: mysql


【解决方案1】:

要获得每组第二个最新的行,您可以使用以下查询

select a.*
from demo a
where  a.demo_var = 100
and (
    select count(*) 
    from demo b
    where b.demo_var = 100
    and a.com_name = b.com_name
    and case when a.updated_date = b.updated_date
        then a.id > b.id 
        else a.updated_date < b.updated_date
        end
) = 1 /* here 1 is for second last , 0 for latest and so on */

请注意,它按updated_date 比较行,因此如果有 2 行相同的 updated_date 和 com_name 则我使用 id 列选择第二个最新行,并假设 id 列默认设置为自动递增

Demo

【讨论】:

    【解决方案2】:

    以下查询将起作用:

    select t.demo_var,t.com_name,max(t.updated_date)
    from
        (
        select demo_var,com_name,upddated_date
        from DemoTable
        where demo_var=100
        and (com_name,updated_date) not in (select com_name,max(updated_date)
                                            from DemoTable
                                            where demo_var=100
                                            group by demo_var,com_name
                                           )
        )t
    group by t.demo_var,t.com_name;
    

    【讨论】:

    • 虽然不是很可扩展
    • @Strawberry 是的,我知道。我正在尝试提出更好的解决方案。一旦我想到会在这里更新。
    • 你写的只是id 1,我要动态查询
    • 您只要求demo_var=100。如果您想要每个demo_var 的结果,只需从查询中删除两个where 子句,它就会起作用
    • 请尝试修改后的查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    相关资源
    最近更新 更多