使用Group By子句查询

问题描述 投票:-1回答:2

我的表有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

提前致谢

sql postgresql greatest-n-per-group
2个回答
1
投票

使用row_number()

select * from
(
select *,row_number() over(partition by department order by last_updated_date desc) as rn from tablename
)A where rn=1

或者您可以使用相关子查询

select * from tablename a 
  where last_updated_date in (select max(last_updated_date) from tablenamae b where a.department=b.department)

1
投票

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

select distinct on (department) * 
from the_table
order by department, last_updated desc;
© www.soinside.com 2019 - 2024. All rights reserved.