oracle 不确定在这种情况下如何使用解码、NVL 和/或 isNull(或其他什么?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2829762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 20:38:08  来源:igfitidea点击:

Not sure how to use Decode, NVL, and/or isNull (or something else?) in this situation

sqloracledecodenvl

提问by RSW

I have a table of orders for particular products, and a table of products that are on sale. (It's not ideal database structure, but that's out of my control.) What I want to do is outer join the order table to the sale table via product number, but I don't want to include any particular data from the sale table, I just want a Y if the join exists or N if it doesn't in the output. Can anyone explain how I can do this in SQL?

我有一张特定产品的订单表和一张打折产品的表。(这不是理想的数据库结构,但这是我无法控制的。)我想做的是通过产品编号将订单表外部连接到销售表,但我不想包含销售表中的任何特定数据,我只想要一个 Y 如果连接存在或 N 如果它不在输出中。谁能解释我如何在 SQL 中做到这一点?

Thanks in advance!

提前致谢!

回答by Hank Gay

You should be able to use the CASEconstruct, and it would look something like this:

您应该能够使用该CASE构造,它看起来像这样:

select
    order.foo,
    case
        when sale.argle is null then 'N'
        else 'Y'
    end
from order
left join sale on order.product_number = sale.product_number;

回答by PaulJ

I nornally use NVL2 for this type of situation...

我通常在这种情况下使用 NVL2...

SELECT col_one
     , NVL2( col_one, 'Y', 'N' )   col_one_exists
     , col_two
     , NVL2( col_two, 'Y', 'N' )   col_two_exists
  FROM ( SELECT '12345'   col_one
              , NULL   col_two
           FROM dual
       )

Would return this:-

会返回这个:-

COL_ONE  COL_ONE_EXISTS  COL_TWO  COL_TWO_EXISTS
12345    Y                         N

回答by Jonathan Leffler

Try (untested):

尝试(未经测试):

SELECT O.*, DECODE(NVL(p.product_num, 'X'), 'X', 'N', 'Y')
  FROM Orders AS o LEFT JOIN Products AS p ON o.Product_Num = p.Product_Num

The NVL will translate nulls in the 'p.product_num' to 'X', which will compare equal to 'X' in the DECODE, generating 'N'; non-null product numbers will be a number, not equal to 'X', and hence will generate a 'Y'.

NVL 会将“p.product_num”中的空值转换为“X”,这将与 DECODE 中的“X”进行比较,生成“N”;非空产品编号将是一个数字,不等于“X”,因此将生成一个“Y”。