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
How to select the comparison of two columns as one column in Oracle
提问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 DECODE
several 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