每个按群组获取最新记录(Get the latest records per Group By SQL)

编程入门 行业动态 更新时间:2024-10-28 19:27:06
每个按群组获取最新记录(Get the latest records per Group By SQL)

我有下表:

----------------------------------------------------------- ID oDate oName oItem oQty oRemarks ----------------------------------------------------------- 1 2016-01-01 A 001 2 2 2016-01-01 A 002 1 test 3 2016-01-01 B 001 3 4 2016-01-02 B 001 2 5 2016-01-02 C 001 2 6 2016-01-03 B 002 1 7 2016-01-03 B 001 4 ff.

我想获得每个名字的最新记录。 所以结果应该是这样的:

----------------------------------------------------------- oDate oName oItem oQty oRemarks ----------------------------------------------------------- 2016-01-01 A 001 2 2016-01-01 A 002 1 test 2016-01-02 C 001 2 2016-01-03 B 002 1 2016-01-03 B 001 4 ff.

有谁知道如何得到这个结果? 谢谢。

I have the following table:

----------------------------------------------------------- ID oDate oName oItem oQty oRemarks ----------------------------------------------------------- 1 2016-01-01 A 001 2 2 2016-01-01 A 002 1 test 3 2016-01-01 B 001 3 4 2016-01-02 B 001 2 5 2016-01-02 C 001 2 6 2016-01-03 B 002 1 7 2016-01-03 B 001 4 ff.

I want to get the latest record for each name. So the result should be like this:

----------------------------------------------------------- oDate oName oItem oQty oRemarks ----------------------------------------------------------- 2016-01-01 A 001 2 2016-01-01 A 002 1 test 2016-01-02 C 001 2 2016-01-03 B 002 1 2016-01-03 B 001 4 ff.

Does anyone know how to do get this result? Thank you.

最满意答案

rank窗口子句允许您根据某些分区对行进行排名,然后您可以选择最上面的那些:

SELECT oDate, oName, oItem, oQty, oRemarks FORM (SELECT oDate, oName, oItem, oQty, oRemarks, RANK() OVER (PARTITION BY oName ORDER BY oDate DESC) AS rk FROM my_table) t WHERE rk = 1

The rank window clause allows you to, well, rank rows according to some partitioning, and then you could just select the top ones:

SELECT oDate, oName, oItem, oQty, oRemarks FROM (SELECT oDate, oName, oItem, oQty, oRemarks, RANK() OVER (PARTITION BY oName ORDER BY oDate DESC) AS rk FROM my_table) t WHERE rk = 1

更多推荐

本文发布于:2023-08-06 17:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:群组   最新   latest   SQL   Group

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!