20

我已经在这里搜索过这个问题但找不到它,如果我们已经在网站上找到它,请重定向我。

我正在寻找一种创建 CTE 的方法,该方法使用另一个 CTE 作为数据来进一步限制。我有一个为我创建报告的 CTE,但我想使用现有 CTE 使用另一个输入来缩小此报告的范围。

我希望我的问题很清楚。

4

4 回答 4

35

您可以将 2 个(或更多)CTE 链接在一起。

例如

with ObjectsWithA as
(
  select * from sys.objects
  where name like '%A%'
),
ObjectsWithALessThan100 as
(
  select * from ObjectsWithA
  where object_id < 100
)
select * from ObjectsWithALessThan100;

或相同的示例,具有更多“拼写”名称/别名:

with ObjectsWithA (MyObjectId , MyObjectName) as
(
  select object_id as MyObjIdAlias , name as MyNameAlias 
  from sys.objects
  where name like '%A%'
),
ObjectsWithALessThan100 as
(
  select * from ObjectsWithA theOtherCte
  where theOtherCte.MyObjectId < 100
)
select lessThan100Alias.MyObjectId , lessThan100Alias.MyObjectName 
from ObjectsWithALessThan100 lessThan100Alias 
order by lessThan100Alias.MyObjectName;
于 2013-06-10T20:34:46.290 回答
12

CTE 可以参考以前的 CTE:

with report as (
      <your query here>
     ),
     reportLimited as (
      select *
      from report
      where foo = @bar
    )
select *
from reportLimited

唯一的规则是引用必须是连续的。没有前向引用。

于 2013-06-10T20:34:29.027 回答
7

当然,只需直接引用 CTE:

WITH Source As
( 
  SELECT * FROM AllData
),
Filtered AS
(
  SELECT * FROM Source WHERE ID = 4
)
SELECT * FROM Filtered
于 2013-06-10T20:35:43.577 回答
0
WITH 
Source ---------1--------- 
As
( 
    SELECT * FROM emp
),
destination----2----------
AS
(
    SELECT * 
    FROM Source 
    WHERE E_id = 4
)

SELECT * FROM destination
于 2014-10-24T09:50:27.070 回答