PostgreSQL-从2列中选择具有复合最大值的行 [英] PostgreSQL - Select row with composite maximum value from 2 columns

查看:246
本文介绍了PostgreSQL-从2列中选择具有复合最大值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据一些简单的规则在PostgreSQL 9.6中为商家选择最佳报价:

I would like to select the best offers for a merchant in PostgreSQL 9.6 according some simple rules:

  • 如果优惠类型不计其​​要价,则优惠要优于另一优惠
  • 如果折扣值相等,则福利类型为ALL的折扣将优于FOOD的折扣
  • 如果折扣和优惠类型都相同,则可以选择任何优惠,例如选择第一个

所以最好的方法不仅是调用max(),还应该使用条件" max(),在该条件下还应检查另一列以确定它是哪一行.

So best is not just a max() call but a "conditional" max() where another column should be inspected too to determine which row it is.

能请你帮忙吗?

模式:

create table offer (
    id bigserial not null,
    discount int4,
    benefit_type varchar(25),
    ...
    merchant_id int8 not null
);

查询(部分):

select merchant_id, max(discount) as max_discount
from offer
group by merchant_id;

DB提供的样品:

id  discount    benefit_type    ... merchant_id
0   10          FOOD                0
1   20          FOOD                0
2   20          ALL                 0
3   30          ALL                 1
4   40          ALL                 1
5   40          FOOD                1
6   40          ALL                 2
7   50          FOOD                2

所需的结果集:

merchant_id     max_discount    benefit_type
0               20              ALL
1               40              ALL
2               50              FOOD

  • 商家0的最佳报价是报价2,因为20 ALL> 20 FOOD.
  • 商人1的最好报价是4,因为40 ALL> 30 ALL.
  • 商人2的最好报价是5,因为50 FOOD> 40 ALL.
  • 推荐答案

    可以使用distinct on()和Benefit_type的自定义排序定义来实现:

    This can be achieved using distinct on() and a custom sort definition for the benefit_type:

    select distinct on (merchant_id) *
    from offer
    order by merchant_id, 
             discount desc, 
             case when benefit_type = 'ALL' then 1 else 2 end;
    

    这倾向于更高的折扣.如果两个折扣相同,则使用ALL的Benefit_type作为平局.

    This prefers higher discount. If two discounts are the same, a benefit_type of ALL is used as the tie-breaker.

    在线示例: http://rextester.com/TFBP17217

    这篇关于PostgreSQL-从2列中选择具有复合最大值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆