在 WHERE 子句中正确使用 COALESCE

编程入门 行业动态 更新时间:2024-10-27 04:34:13
本文介绍了在 WHERE 子句中正确使用 COALESCE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

有人可以解释为什么在下面的条件下,coalesce 在 where 子句中不起作用吗?在这种情况下,我们如何在不改变以下合并条件的情况下正确使用合并,并且只针对被破坏的 = Y?

Can someone explain why coalesce doesn't work in the where clause given the following conditions below? How do we use coalesce correctly in this case without changing the below coalesce conditions and only for spoiled = Y?

餐桌水果:

  ITEM_NAME     ITEM_NO     SPOILED
  Apples        A15354        N 
  Bananas       BYHUG1        N
  Grapes        GR0013        Y     
  Oranges       ORULYE        N
  Guavas        GUOIUW        Y

查询:

  select fruit.item_name
  from fruit
  where fruit.item_no = coalesce('A15354','CURR_NOT_IN_TABLE','GR0013','GUOIUW')
  and fruit.spoiled = 'Y'

使用上面的查询不会返回任何内容.期望的输出应该是葡萄.

Using the query above will not return anything. Desired output should be grapes.

期望的输出:

  Grapes

推荐答案

我们可以在这里使用 ROW_NUMBER 来选择你想要的优先级:

We can use ROW_NUMBER here to select what you want with priorities:

WITH cte AS (
    SELECT f.*, ROW_NUMBER() OVER (ORDER BY DECODE(ITEM_NO, 'A15354', 1,
                                                            'CURR_NOT_IN_TABLE', 2,
                                                            'GR0013', 3,
                                                            'GUOIUW', 4, 5)) rn
    FROM fruit f
    WHERE spoiled = 'Y'
)

SELECT ITEM_NAME
FROM cte
WHERE rn = 1;

这里的想法是为每个被损坏的项目分配一个从 1 到 5 的优先级.我们使用 ROW_NUMBER 来生成一个序列,它总是从 1 开始,这是最高的可用优先级.

The idea here is to assign a priority from 1 to 5 for each item which is spoiled. We use ROW_NUMBER to generate a sequence always starting with 1 being the highest available priority.

这篇关于在 WHERE 子句中正确使用 COALESCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:48:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   正确   COALESCE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!