SQL Oracle中如何将两列的比较选择为一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4827751/
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-01 09:05:30  来源:igfitidea点击:

How to select the comparison of two columns as one column in Oracle

sqloracleselect

提问by Vito De Tullio

I cannot figure out how to add a column to my SELECT query indicating whether two columns contain the same data in Oracle.

我无法弄清楚如何向我的 SELECT 查询添加一列,以指示两列是否包含 Oracle 中的相同数据。

I would like to write a query like:

我想写一个查询,如:

select column1, column2, column1=column2 from table

and, if I have this table:

而且,如果我有这张桌子:

+---------+---------+
| column1 | column2 |
+---------+---------+
| value1  | value1  |
| value2  | value3  |
| value4  | value4  |
+---------+---------+

get a result like:

得到如下结果:

+---------+---------+-----------------+
| column1 | column2 | column1=column2 |
+---------+---------+-----------------+
| value1  | value1  | true            |
| value2  | value3  | false           |
| value4  | value4  | true            |
+---------+---------+-----------------+

What is the correct syntax to do this?

执行此操作的正确语法是什么?

回答by vc 74

If you want to consider null values equality too, try the following

如果您也想考虑空值相等,请尝试以下操作

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

回答by Ronnis

I stopped using DECODEseveral years ago because it is non-portable. Also, it is less flexible andless readable than a CASE/WHEN.

DECODE几年前我停止使用,因为它不便携。此外,它是不够灵活小于a可读CASE/WHEN

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

但是,由于解码处理 NULL 的方式,您可以使用一种巧妙的“技巧”。在解码中,NULL 等于 NULL。可以利用它来判断两列是否不同,如下所示。

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

回答by Zsolt Botykai

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

HTH