你能为Common Tableexpression式创build嵌套的WITH子句吗?

WITH y AS ( WITH x AS ( SELECT * FROM MyTable ) SELECT * FROM x ) SELECT * FROM y 

有这样的工作吗? 我早些时候尝试过,但我无法得到它的工作。

虽然不是严格嵌套的,但可以使用公用表expression式来重用之前的查询。

要做到这一点,你正在寻找的声明的forms将是

 WITH x AS ( SELECT * FROM MyTable ), y AS ( SELECT * FROM x ) SELECT * FROM y 

您可以执行以下操作,这被称为recursion查询:

 WITH y AS ( SELECT x, y, z FROM MyTable WHERE [base_condition] UNION ALL SELECT x, y, z FROM MyTable M INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition] ) SELECT * FROM y 

您可能不需要此function。 我已经完成了以下工作,以更好地组织我的查询:

 WITH y AS ( SELECT * FROM MyTable WHERE [base_condition] ), x AS ( SELECT * FROM y WHERE [something_else] ) SELECT * FROM x 

随着embedded式不工作,但它连续工作

 ;WITH A AS( ... ), B AS( ... ) SELECT * FROM A UNION ALL SELECT * FROM B 

编辑修正了语法…

另外,看看下面的例子

SQLFiddle DEMO

这些答案是相当不错的,但只要得到正确的订单项目,你最好看这篇文章http://sqlblog.com/blogs/adam_machanic/archive/2015/04/07/re-inventing -the-recursioncte.aspx

这是他的查询的一个例子。

 WITH paths AS ( SELECT EmployeeID, CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath FROM EmployeeHierarchyWide WHERE ManagerID IS NULL UNION ALL SELECT ehw.EmployeeID, CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath FROM paths AS p JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID ) SELECT * FROM paths order by FullPath 

我们可以创build嵌套的cte.please,请参阅下面的示例中的cte

 ;with cte_data as ( Select * from [HumanResources].[Department] ),cte_data1 as ( Select * from [HumanResources].[Department] ) select * from cte_data,cte_data1 

我试图测量事件之间的时间,除了开始和结束之间有多个进程的项之外。 我需要在其他单行stream程的背景下。

我在第N个cte中使用了一个带内连接的select作为我的select语句。 第二个cte我需要提取X上的开始date和Y上的结束date,并使用1作为左连接的id值,把它们放在一行上。

为我工作,希望这有助于。

 cte_extract as ( select ps.Process as ProcessEvent , ps.ProcessStartDate , ps.ProcessEndDate -- select strt.* from dbo.tbl_some_table ps inner join (select max(ProcessStatusId) ProcessStatusId from dbo.tbl_some_table where Process = 'some_extract_tbl' and convert(varchar(10), ProcessStartDate, 112) < '29991231' ) strt on strt.ProcessStatusId = ps.ProcessStatusID ), cte_rls as ( select 'Sample' as ProcessEvent, x.ProcessStartDate, y.ProcessEndDate from ( select 1 as Id, ps.Process as ProcessEvent , ps.ProcessStartDate , ps.ProcessEndDate -- select strt.* from dbo.tbl_some_table ps inner join (select max(ProcessStatusId) ProcessStatusId from dbo.tbl_some_table where Process = 'XX Prcss' and convert(varchar(10), ProcessStartDate, 112) < '29991231' ) strt on strt.ProcessStatusId = ps.ProcessStatusID ) x left join ( select 1 as Id, ps.Process as ProcessEvent , ps.ProcessStartDate , ps.ProcessEndDate -- select strt.* from dbo.tbl_some_table ps inner join (select max(ProcessStatusId) ProcessStatusId from dbo.tbl_some_table where Process = 'YY Prcss Cmpltd' and convert(varchar(10), ProcessEndDate, 112) < '29991231' ) enddt on enddt.ProcessStatusId = ps.ProcessStatusID ) y on y.Id = x.Id ), 

….其他种类

Interesting Posts