Constructing a temporary table in Oracle SQL

故事扮演 提交于 2019-12-11 06:39:32

问题


I am trying to make a sub-table that "stores" a decode between two values, because I need to use that decode multiple times. Let's say these are my tables:

Table Person
Name    Number_name
Jeremy  One
Thomas  Two
Stephen Three

my current SQL looks like this:

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)

What I'd like to be able to do is something like this:

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)
...

where my_temp_table is constructed during that query (it ceases to exist when the query finishes running) and will look like

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

And hopefully I can do this without the ol' "select one name,1 num from dual union all ..."

Is this doable?


回答1:


The WITH clause is sounds like the closest thing to what you're describing. But that requires that you generate the data somehow. Selecting from DUAL is likely the easiest option

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>>

Since you don't want to union a bunch of queries, you could do something like

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


来源:https://stackoverflow.com/questions/10730364/constructing-a-temporary-table-in-oracle-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!