在 Oracle SQL 中连接 CASE
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19039338/
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
CONCATENATE a CASE in Oracle SQL
提问by Cheddar Smith
I need to run a CASE
expression on a number of columns, the columns are Boolean, so if it's 0 I need to populate the column with the column name and if it's 1, I ignore the column/value. I then need to concatenate all these columns into one. Is it possible to do this in Oracle SQL?
我需要CASE
在多列上运行一个表达式,这些列是布尔值,所以如果它是 0,我需要用列名填充列,如果它是 1,我会忽略列/值。然后我需要将所有这些列连接成一个。是否可以在 Oracle SQL 中执行此操作?
I've tried this:
我试过这个:
Select
||CASE
WHEN COL_A = 0 THEN 'COL_A'
ELSE ''
END||','
||CASE
WHEN COL_B = 0 THEN 'COL_B'
ELSE ''
END||
from ABC.123
Can this even been done? If not this way are there any other ways?
这甚至可以做到吗?如果不是这种方式还有其他方式吗?
回答by DCookie
Yes, it will work (if you clean up the syntax). Here's a simple example:
是的,它会起作用(如果您清理语法)。这是一个简单的例子:
with q as (
select 0 col_a, 1 col_b, 'Rec 1' id from dual
union all
select 1, 0, 'Rec 2' from dual
union all
select 0, 0, 'Rec 3' from dual
)
Select id,
CASE
WHEN COL_A = 0 THEN 'COL_A'
ELSE ''
END||','
||CASE
WHEN COL_B = 0 THEN 'COL_B'
ELSE ''
END "TheString"
from q
Result:
结果:
ID TheString
------- -------------------
Rec 1 COL_A,
Rec 2 ,COL_B
Rec 3 COL_A,COL_B