我正在尝试实现以下查询的逻辑:
select ......
from (select ..... from ... complex and long query #1) R1
(select ..... from ... complex and long query #2) R2
Where
NOT ( @DateStart > R2.IstEnde OR @DateEnd <= R2.IstStart)
OR
(
(select count(*)
from R2 // <---- BUG IS HERE
Where R2.IsOutsideTaskTimeFrame = 1 AND R2.IsManuallyFixed = 1
) > 0
)
order BY R2.PersonName, R1.YearOfWeek, R1.Week
哪个明显不起作用,因为我试图在条件“ count()”中“重用” R2。
我正在基于“ .NET Linq”逻辑编写此代码,在这里我们可以“重用”先前的查询。
我什至可以编写这样的逻辑:“重用”先前的查询,而不再重复吗?
最佳答案
也许您正在寻找CTE - Common Table Expression:
;WITH R1 AS
(SELECT ...)
,R2 AS
(SELECT ...)
SELECT * FROM R1
... use R1 and R2 like any other table here (it's called "derived table")
如果需要独立查询中的结果,则可以填充声明的表变量或临时表。
关于c# - SQL Server-重用先前的查询-与Linq相似的逻辑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40994148/