【问题标题】:Constructing a temporary table in Oracle SQL在 Oracle SQL 中构建临时表
【发布时间】:2012-05-30 14:47:44
【问题描述】:

我正在尝试创建一个在两个值之间“存储”解码的子表,因为我需要多次使用该解码。假设这些是我的表格:

Table Person
Name    Number_name
Jeremy  One
Thomas  Two
Stephen Three

我当前的 SQL 如下所示:

SELECT
    decode (number_name,
    'one',1,
    'two',2,
    'three',3,
    'four',4)
    num
    FROM person where name = 'Jeremy'
    and (some other condition)
UNION SELECT
    decode (number_name,
    'one',1,
    'two',2,
    'three',3,
    'four,4)
    num
    FROM Person
    where Name <> "Jeremy"
    and (some other condition)

我想做的是这样的:

SELECT num from my_temp_table where name = "Jeremy" and (some other condition)
union select num from my_temp_table where name <> "Jeremy" and (some other condition)
...

my_temp_table 在该查询期间构造的位置(当查询完成运行时它不再存在)并且看起来像

Table my_temp_table
Name  num
One   1
Two   2
Three 3
Four  4

希望我可以在没有“选择一个名称,1 个来自双重联合的所有...”的情况下做到这一点

这可行吗?

【问题讨论】:

  • 确定性函数怎么样?亚历山德罗

标签: sql oracle temp-tables


【解决方案1】:

WITH 子句听起来与您所描述的内容最接近。但这需要您以某种方式生成数据。从DUAL 中选择可能是最简单的选择

WITH my_temp_table AS (
  SELECT 'One' name, 1 num from dual union all
  SELECT 'Two', 2 from dual union all
  SELECT 'Three', 3 from dual union all
  SELECT 'Four', 4 from dual
)
SELECT *
  FROM my_temp_table 
       JOIN person ON (<<some join condition>>)
 WHERE <<some predicate>>

由于您不想合并一堆查询,您可以执行类似的操作

WITH my_temp_table AS (
  select level num,
         initcap( to_char( to_date( level, 'J' ),
                           'JSP' )) name
    from dual
 connect by level <= 4
)
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2011-04-26
    • 2013-03-19
    • 2018-12-18
    • 2011-04-10
    相关资源
    最近更新 更多