我们可以加入我们在sql中创建的同一个表吗?

时间:2013-08-12 09:17:32

标签: sql sas

我想知道是否有可能加入我们正在创建的同一个表,而不必在加入后复制整个表代码。

例如:

create table tableC as
select * 
from (
    select *, min(a) as minA 
     from tableB
     group by id) as tb0 
) 
join (select *, min(a) as minA 
    from tableB
    where min(a) = 1) as tb1
on tb1.id = tb0.id;

在这个例子中,连接不是必需的,但在某些情况下仍然是。 我的问题是,我们可以使用第一个块代码中的表来执行连接,而无需在连接后复制整个代码吗?

更准确地说,我们可以做一些像

这样的事情
create table tableC as
select * 
from (
    select *, min(a) as minA 
     from tableB
     group by id) as tb0 
) 
join (select *
    from **tb0**
    where **minA** = 1) as tb1
on tb1.id = tb0.id;

由于

2 个答案:

答案 0 :(得分:2)

嗯,干净简单的方法是创建一个视图:

proc sql noprint;
    create view myView as
    select *, min(a) as minA 
    from tableB
    group by id;
quit;

proc sql noprint;
    select *
    from myView as tb0
    join
    (
        select *
        from myView
        where minA=1
    ) as tb1
    on tb1.id=tb2.id;
quit;

它有效(如果我没有写错字),它可以防止代码重复,看起来更干净。 (后者当然是个人意见的问题)

我想知道你想象这个特定连接有用的场景。

答案 1 :(得分:1)

在SAS中,您无法直接执行该功能。在使用with块执行的TSQL中,但SAS(当前)不支持该块。这看起来大致如下:

with tb0 as (
    select *, min(a) as minA 
     from tableB
     group by id)
select * from tb0 
 inner join
 (select 1 from tb0 where min(something)) tb1
  on tb0.id=tb1.id;