如何从同一表中选择具有多个别名的同一列?

时间:2018-07-09 01:43:36

标签: sql oracle11g

我需要从表中选择具有以下组合的值

SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '11AX';
SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '34XA';
SELECT Details FROM  Avenger   WHERE Id = '1' and KEY = '11AZ';
SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '11ZA';

在单个查询中,我知道我可以使用

SELECT * FROM Avenger WHERE ID='1';

但是我需要使用所有选定的值,并在单个查询中将其分配给四个变量

我可以使用的任何想法或解决方案吗?

Id  Key Details
1   11AX    Mark 
1   34XA    Bruce 
1   11AZ    Mr. Green
1   11ZA    Hulk
2   11AX    Robert jr.
2   34XA    Toney 
2   11AZ    Iron Man
2   11ZA    Arrogant
3   11AX    Thor
3   34XA    Asgard
3   11AZ    God
3   11ZA    Hamer

3 个答案:

答案 0 :(得分:1)

我们可以尝试在此处交替使用REGEXP_LIKE

SELECT *
FROM yourTable
WHERE Id = '1' AND REGEXP_LIKE("KEY", '11AX|34XA|11AZ|11ZA')

实际上,我不确定您是否打算在原始查询中使用LIKE。您可能真的只想这样做:

SELECT *
FROM yourTable
WHERE Id = '1' "KEY" IN ('11AX', '34XA', '11AZ', '11ZA')

答案 1 :(得分:1)

我认为您想要一个case表达式:

select details,
       (case when key like '11AX' then 1
             when key like '34XA' then 2
             when key like '11AZ' then 3
             when key like '11ZA' then 4
        end) as flag
from avenger a
where id = 1;

如果只想使用一个表达式选择值,请以in开头:

where id = 1 and key in ('11AX', '34XA', '11AZ', '11ZA')

如果要将值作为单个字符串传递,则regexp_like()可以起作用:

where id = 1 and regexp_like(key, '^11AX|34XA|11AZ|11ZA$')

两个注意事项:

  • 该模式已锚定,因此仅匹配完整的key
  • regexp_like()通常不使用索引,因此对于性能而言,=in是更好的选择。

也许你打算:

select max(case when key like '11AX' then details end) as deails_11ax,
       max(case when key like '34XA' then details end) as details_34XA,
       max(case when key like '11AZ' then details end) as details_11AZ,
       max(case when key like '11ZA' then details end) as details_11AZ
from avenger a
where id = 1;

这将返回一行包含四列。

答案 2 :(得分:1)

认为我了解您想要这个:

select 
    (SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '11AX') as var1,
    (SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '34XA') as var2,
    (SELECT Details FROM  Avenger   WHERE Id = '1' and KEY = '11AZ') as var3,
    (SELECT Details FROM  Avenger   WHERE Id = '1' AND KEY LIKE '11ZA') as var4
    from dual

还有一个pivot选项