【问题标题】:Return based on values selected根据选择的值返回
【发布时间】:2020-11-05 23:33:36
【问题描述】:

我真的不知道如何正确表达标题,所以如果标题令人困惑,请原谅。

这是我面临的情况: 我有一个表...假设它包含以下行。

Name  | Value
----- | ----
John  | 1
Mary  | 2
Jack  | 3
Jim   | 4

这是 PL/SQL 要求:

  1. 如果 John 存在,则返回 John 及其值。
  2. 如果 John 不存在,但 Mary 存在,则返回 Mary 和她的值。
  3. 如果 John 和 Mary 都不存在,则返回 Jack 或 Jim 中的任何一个 具有更高的价值。

我可以使用游标遍历表格并测试每一行,但我想知道是否还有其他更有效的方法。

谢谢!

【问题讨论】:

    标签: sql oracle oracle11g sql-order-by case


    【解决方案1】:

    不需要游标和循环。您可以在单个查询中执行此操作,使用条件排序和 fetch 子句:

    select *
    from mytable
    order by 
        case name when 'John' then 1 when 'Mary' then 2 else 3 end, 
        value desc
    fetch first row only 
    

    或者,如果您是 Oracle 的 12c 之前的版本,其中 fetch 子句不可用:

    select name, value
    from (
        select t.*, 
            row_number() over(order by 
                case name when 'John' then 1 when 'Mary' then 2 else 3 end, 
                value desc
            ) rn
        from mytable t
    ) t
    where rn = 1
    

    【讨论】:

    • @JohnnyWu:这可以满足您的要求。这是一个 db fiddle:dbfiddle.uk/…
    • @GMB...我的道歉...这确实有效!杰出的!你介意解释一下内部选择吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多