如何在sql中重用子查询?

时间:2013-02-20 18:30:04

标签: sql sql-server tsql subquery

我有以下查询

select columns
from (select columns1
      from result_set
      where condition_common and condition1) as subset1
      join
      (select columns2
       from result_set
       where condition_common and condition2) as subset2 
      on subset1.somekey = subset2.somekey

我想以某种方式重用

select columns
from result_set
where condition_common

我已经过度简化了上面的查询,但上面的选择实际上是庞大而复杂的。我不想承担确保两者同步的负担

我没有任何以编程方式重用它的方法。排除了T-SQL。我只能写简单的查询。这是应用限制。

有没有办法在单个语句中重用相同的子查询

1 个答案:

答案 0 :(得分:22)

如果您使用的是SQL Server 2005 +,请使用Common Table Expression(CTE):

with cte as (
      select columns
      from result_set
      where condition_common
    )
select columns
from cte  as subset1
      join
      cte as subset2 
         on subset1.somekey = subset2.somekey
where otherconditions