想象这种格式的数据:
Customer, Object, Price
[William, Orange, 100p
William, Apple, 80p
William, Banana 60p
Casper, Cola, 150p
Casper, Beer, 120p
Casper, Peanuts, 200p]
我有兴趣为每个买家提取最便宜的商品以及实际商品。
输出应该看起来像这样。
Customer, MostExpItem, MostExpCost, LeastExpItem, LeastExpCost
William, Orange, 100p, Banana, 60p
Casper, Peanuts, 200p, Beer, 120p
任何指针?我可以使用group by轻松提取最小值/最大值。此问题是否需要子查询?
您可以使用窗口功能:
select
customer,
max(object) filter(where price = most_exp_price) most_exp_item,
most_exp_price,
max(object) filter(where price = less_exp_price) less_exp_item,
less_exp_price
from (
select
t.*,
max(price) over(partition by customer) most_exp_price,
min(price) over(partition by customer) less_exp_price
from mytable t
) t
where price in (max_price, min_price)
group by customer