寻找 SQL-Server 函数来识别 min/max 行并从这些行中提取信息

Looking for SQL-Server function to identify min/max row and extract information from these rows

想象一下这种格式的数据:

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 轻松提取 min/max 值。这个问题需要子查询吗?

您可以使用 window 函数:

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 (most_exp_price, less_exp_price)
group by customer

子查询计算每个客户的最高和最低价格。外部查询过滤最高价和最低价,按客户聚合并显示相应的项目。

在 Postgres 中,如果您想避免子查询,可以使用数组:

select customer,
       min(price),
       (array_agg(order by price))[1],
       max(price),
       (array_agg(order by price desc))[1]
from t
group by customer;