select customer_id,
customer_name,
product_name latest_order
from (
select d.customer_id,
customer_name,
product_name,
row_number() over (partition by customer_id order by order_date desc) rk
from orders d
join customers c on d.customer_id=c.customer_id
join products p on d.product_id=p.product_id
) t
where rk=1
order by customer_id
想要对一列group by 但是要显示的却是另外一列时,此时应考虑放弃groupby方法,转而使用窗口函数,如果最后展示的是窗口函数的序号,那么直接在主查询中使用窗口函数即可;但是如果最后展示的只是窗口函数排序后对应的某一列,那么在子查询中使用主函数,再在主查询中用where进行限制,以限制主查询中显示的信息。

京公网安备 11010502036488号