【问题标题】:If then else conditions in order by clauseif then else 条件按子句顺序排列
【发布时间】:2021-12-06 12:36:42
【问题描述】:

我有一个包含以下字段的表格:

  • 身份证
  • 折扣金额
  • discount_expires_at

如何查询所有记录并按discount_amount 排序,但仅当discount_expires_at 大于当前时间?

无论如何,所有行都必须包含在内,但只有当折扣尚未过期时,它们才应首先出现。如果已过期,则必须按 id 降序排序

【问题讨论】:

  • 如果discount_expires_at小于当前时间,那么记录应该如何排序?

标签: sql postgresql sql-order-by


【解决方案1】:

按复合值降序排列,(1, discount_amount) 如果折扣仍然有效,(0, id) 如果没有。第一个常量 - 1 或 0 - 使过期折扣排在活动折扣之后。

select * from the_table
order by 
 case
   when discount_expires_at > current_timestamp then (1, discount_amount)
   else (0, id)
 end desc;

【讨论】:

    【解决方案2】:

    您可以简单地使用 case 表达式:

    select *
    from t
    order by
        case when discount_expires_at > current_timestamp then 1 else 2 end,
        case when discount_expires_at > current_timestamp then discount_amount end desc,
        case when discount_expires_at > current_timestamp then null else id end desc
    

    表达式discount_expires_at > current_timestamp 条件要么为真,要么为假/未知;根据这两种可能的结果选择所需的列。

    【讨论】:

    • 这不会对第一组行进行排序,只会在其他行之前列出它们
    • 不是我阅读问题的方式
    • 我想包含所有行。如果有 10 行有活动折扣(未过期),则必须在前 10 个位置,并且它们的位置必须由discount_amount 决定。没有有效折扣的其余行必须在前 10 行之后,并且必须按其 id 排序
    • 一切都在下降。我想要最优惠的,然后是最新的。而且,这和帕特里克的答案有什么区别,哪个更高效
    • 我已经更新了答案。我假设 discount_amount 和 id 是数字且可比较的。
    猜你喜欢
    • 2023-03-08
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多