[英]IF ELSE Statement and Insert a new Column
I've been trying research online on how to combine "If" statements into my query. 我一直在尝试在线研究如何将“ If”语句组合到查询中。 Suppose I wanted to create a query such that I want to create a extra column called "Description", and then include a if else statement such that "If Value = "A" then Description = "A", If Value = "B" then Description = "B", so on and so on. The problem is, since I have minimal access (not admin) to the databases. I can't create tables. I can only query the tables in oracles and export it out. Will that be an issue in terms of creating an extra column? 假设我想创建一个查询,以便创建一个名为“ Description”的额外列,然后包含一个if else语句,例如“ If Value =“ A” then Description =“ A”,If Value =“ B”然后是Description =“ B”,依此类推等等。问题是,由于我对数据库的访问权限最少(不是admin),所以无法创建表,只能在oracles中查询表并将其导出。就创建额外的列而言,这将是一个问题吗?
Original: 原版的:
ID Value
1 A
2 B
3 C
Want something like: 想要类似的东西:
ID Value Description(New Column)
1 A Apple
2 B Bacon
3 C Candy
Okay. 好的。 I have no idea what I was doing below but it would be something like that? 我不知道我在下面做什么,但这会是那样吗? Where to I insert a new column called "Description"? 在哪里插入新列“说明”?
Select A.ID, B.Value
From Table A
Join Table B
On A.ID = B.ID
Where ID in ('1','2','3')
If b.Value = 'A' then
(Description = "Apple")
If b. value = 'B' then
(Description = "Bacon")
Group by A.ID, B.Value
You can use CASE
: 您可以使用CASE
:
SELECT A.ID, B.Value,
CASE B.Value
WHEN 'A' THEN 'Apple'
WHEN 'B' THEN 'Bacon'
WHEN 'C' THEN 'Candy'
END AS Description
FROM TableA A
JOIN TableB B ON A.ID = B.ID
you can do it like below 你可以像下面这样
SELECT A.ID, A.Value, B.Description
FROM TABLEA A
JOIN ( SELECT 'A' as Value, 'Apple' as Description from dual
UNION
SELECT 'B' as Value, 'Bacon' as Description from dual
) T
on A.Value= B.Value
I'm not sure why you need to join the table to itself. 我不确定为什么您需要将表本身连接起来。 Also, I presume you're not really trying to do this with a table named "table". 另外,我认为您并不是真的要使用名为“ table”的表来执行此操作。
CASE would do the job, as in Barmar's answer. 正如Barmar的回答一样,CASE可以胜任。 I find DECODE more readable when the logic is this simple, but it's really a matter of taste. 当逻辑如此简单时,我发现DECODE更具可读性,但这实际上是一个品味问题。 CASE is more flexible, which is not a matter of taste, but you don't need that flexibility here. CASE更具灵活性,这与口味无关,但是您在这里不需要这种灵活性。
select id
,value
,decode( value
,'A', 'Apple'
,'B', 'Bacon'
,'C', 'Candy' ) as Description
from table;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.