sql – 在Oracle中创建CTE

前端之家收集整理的这篇文章主要介绍了sql – 在Oracle中创建CTE前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在Oracle中创建一个CTE,它不从现有表中进行选择,而是将数据插入其中.目前,我正在创建一个表,然后在查询完成后删除它.有没有办法创建一个有效地做同样事情的CTE?这是我目前的代码
create table RTG_YEARS
(YR date);

insert into RTG_YEARS values (to_date('2013-01-01','yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2013-12-31','yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2014-01-01','yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2014-12-31','yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2015-01-01','yyyy-mm-dd'));
insert into RTG_YEARS values (to_date('2015-12-31','yyyy-mm-dd'));

解决方法

您可以通过从dual中选择日期值来创建公用表表达式(CTE,subquery factoring等),并将它们组合在一起:
with RTG_YEARS (YR) as (
  select to_date('2013-01-01','yyyy-mm-dd') from dual
  union all select to_date('2013-12-31','yyyy-mm-dd') from dual
  union all select to_date('2014-01-01','yyyy-mm-dd') from dual
  union all select to_date('2014-12-31','yyyy-mm-dd') from dual
  union all select to_date('2015-01-01','yyyy-mm-dd') from dual
  union all select to_date('2015-12-31','yyyy-mm-dd') from dual
)
select * from RTG_YEARS;

YR       
----------
2013-01-01
2013-12-31
2014-01-01
2014-12-31
2015-01-01
2015-12-31

与CTE无关,但您可以使用date literals减少输入:

with RTG_YEARS (YR) as (
  select date '2013-01-01' from dual
  union all select date '2013-12-31' from dual
  union all select date '2014-01-01' from dual
  union all select date '2014-12-31' from dual
  union all select date '2015-01-01' from dual
  union all select date '2015-12-31' from dual
)
select * from RTG_YEARS;

猜你在找的MsSQL相关文章