如何解决按列查询最后一个数据组
我有此数据;
date owner p.code product
---- ----- ----- ------
21.08.2020 Micheal 5 apple
22.08.2020 Micheal 5 apple
15.08.2020 George 4 biscuit
14.08.2020 George 4 biscuit
10.08.2020 Micheal 4 biscuit
23.08.2020 Alice 2 pear
15.08.2020 Alice 2 pear
14.08.2020 Micheal 2 pear
11.08.2020 Micheal 2 pear
我想将它们归类为产品,并显示最后的日期和最后的所有者。
像这样;
date owner p.code product
---- ----- ------ ------
22.08.2020 Micheal 5 apple
15.08.2020 George 4 biscuit
23.08.2020 Alice 2 pear
解决方法
您可以使用窗口功能:
select *
from (
select t.*,row_number() over(partition by product order by date desc) rn
from mytable t
) t
where rn = 1
,
在Oracle中,您可以使用group by
来对此表述:
select product,code,max(date) as max_date,max(owner) keep (dense_rank first order by date desc) as owner_at_max_date
from t
group by product,code;
keep
语法是Oracle实现first()
聚合函数的相当冗长的方式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。