我的表有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
预先感谢
答案 0 :(得分: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 :(得分:1)
在Postgres中,使用distinct on ()
select distinct on (department) *
from the_table
order by department, last_updated desc;