首页 > 解决方案 > 使用 Group By 子句查询

问题描述

我的表有 last_updated_date、department 和其他一些字段,我想写一个查询来获取所有列,在每个部门的 last_updated_row 中最高。我尝试使用 group by 子句编写,但没有得到所有行。

   id   name    department      last_updated_date
    1   Manu    Maths       22/01/2019
    2   Anil    Maths       23/01/2019
    3   Kala    Maths       24/01/2019

    4   Deepak  Science     22/02/2019
    5   Krish   Science     23/02/2019
    6   Kannan  Science     24/02/2019

    7   Sai     English     02/12/2018
    8   Sunil   English     03/12/2018
    9   Mala    English     04/12/2018
    10  Kola    English     04/12/2018

我想回来

    3   Kala    Maths       24/01/2019
    6   Kannan  Science     24/02/2019
    9   Mala    English     04/12/2018
or
    10  Kola    English     04/12/2018

如果两个 last_updated_date 相同,则查询应检索 last_updated_date 中的任何一个。

在这里,我使用日期字段的时间戳。所以我的 last_modified_date 看起来像 2019-02-07 17:26:49.209

提前致谢

标签: sqlpostgresqlgreatest-n-per-group

解决方案


在 Postgres 中,这种类型的查询通常最有效地使用distinct on ()

select distinct on (department) * 
from the_table
order by department, last_updated desc;

推荐阅读