按列查询上次数据
Query Last data group by column
我有这个数据;
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
您可以使用 window 函数:
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()
聚合函数的相当冗长的方式。
我有这个数据;
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
您可以使用 window 函数:
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()
聚合函数的相当冗长的方式。