如何在sql中重用子查询? [英] How to reuse a sub query in sql?

查看:38
本文介绍了如何在sql中重用子查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下查询

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

我把上面的查询过分简化了,但上面的选择实际上是巨大而复杂的.我不想承担确保两者同步的负担

I have oversimplified the above query, but the above select in reality is huge and complicated. I dont want to have the burden of making sure both are in sync

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

I dont have any means of programmatically reusing it. T-SQL is ruled out. I can only write simple queries. This is an app limitation.

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

Is there a way to reuse same subquery, in a single statement

推荐答案

使用 通用表表达式 (CTE) 如果您使用的是 SQL Server 2005+:

Use a Common Table Expression (CTE) if you're using SQL Server 2005+:

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

这篇关于如何在sql中重用子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆