将CTE加入主查询

时间:2017-06-07 11:26:22

标签: sql-server

如何将CTE加入主查询?

(ps:再次感谢你 - 这个社区很棒)

 With tempCTE1locws ([1stchargeableweights], movementref, lastdate)
as 
(Select  
SUM(c.[Chargeable Weight]) AS [1stchargeableweights], 
mm.MovementRef [movementref], 
MAX (ts.systemstamp) [lastdate]

FROM      dbo.whsConsignment wc
INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
inner join dbo.movMovement mm on mm.MovementID = m.MovementID
INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
AND wc.whsHeaderID = wh.WhsHeaderID
AND wc.StatusCode = 'NL'
AND c.[Service Type] = 'F'
AND ts.SlackNoSlack = 'slack' 
or ts.slacknoslack like 'slack - tripped%'
WHERE wh.ArrDepDate BETWEEN @StartDate AND @EndDate
GROUP by mm.MovementRef),

我想将此CTE加入motionref上的dbo.movmovement。但是,写它就像

From dbo.movmovement m 
Inner join dbo.tempCTE1locws locws on locws.movementref = m.movementref 

根本不起作用。

1 个答案:

答案 0 :(得分:0)

因此,您应该通过这个主题获得优秀的答案。 Multiple CTE in single query

引用已接受的答案

  

在顶部和任何公用表中使用关键字WITH一次   表达式(CTE)是递归的(rCTE)您必须添加关键字   即使不是所有的CTE都是递归的,也在顶部回归:

WITH RECURSIVE
  cte1 AS (...)  -- can still be non-recursive
, cte2 AS (SELECT ...
           UNION ALL
           SELECT ...)  -- recursive term
, cte3 AS (...)

SELECT ... FROM cte3 WHERE ...

这就是您在CTE定义中需要的原因。

你的错误即将来临,因为你有一个错字。

  

临时' tempCTE1locwns'附近的语法错误。这是我得到的错误

查看CTE名称中的额外n;它应该是tempCTE1locwns而不是tempCTE1locwns