我希望能够在查询的输出上运行自我内部联接。 在最简单的情况下,执行自我INNER JOIN非常简单:
SELECT *
FROM A a1 INNER JOIN
A a2 ON
a1.key = a2.key
问题是我需要在另一个内连接的输出上执行此自内连接。像
这样的东西SELECT *
FROM DATA.A A INNER JOIN
DATA.B B
ON A.key = B.key output /* output is the dataset I am interested in */
INNER JOIN
(FROM DATA.A A INNER JOIN
DATA.B B
ON A.key = B.key output2) /* same code to get output, so that I can self reference */
ON
OUTPUT.key_alt = OUTPUT2.key_alt
有可能这样做吗?我无法将output
存储在我的数据库中。
答案 0 :(得分:1)
在SQL Server中:
我更喜欢使用common table expression来做这类事情。在我看来,它让事情更具可读性。
with cte as (
select *
from data.A as A
inner join data.B as B
on A.key = B.key
)
select ...
from cte as o
inner join cte as i
on o.key = i.key
您可以使用标准子查询来实现此目的。
select o.*
from (
select *
from data.A as A
inner join data.B as B
on A.key = B.key
) as o
inner join (
select *
from data.A as A
inner join data.B as B
on A.key = B.key
) as i
on o.key = i.key