sql - 使用 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
提前致谢
解决方案
在 Postgres 中,这种类型的查询通常最有效地使用distinct on ()
select distinct on (department) *
from the_table
order by department, last_updated desc;
推荐阅读
- pandas - pandas 数据透视表 DF 的索引计数
- python-3.x - Python根据属性获取类对象名称
- javascript - Firefox 中的 JS MIME 警告。不加载脚本
- azure - 如何从 Dynamics 365 而不是 GUID 获得真正的价值?
- pointers - 优化:指针的vector.erase()
- ios - 完成上一条后如何多次绘制相同的贝塞尔路径?
- c - 在提交时给出运行时错误,但在 leetcode 问题上的自定义测试用例上给出正确的输出
- angular - Angular:自定义管道的测试用例
- powerbi - PowerBi 根据 ID、问题状态和版本查找 SLA 状态
- php - 在主页中获取客户 ID - Magento 2