SQL 服务器 - 重复使用子查询返回的值而不再次执行子查询

SQL Server - Reuse the value returned by the subquery without executing the subquery again

我在我的 select 查询中使用了一个子查询,它给我一个聚合值,该子查询有 4-5 行,涉及连接和条件。

现在我需要在我的外部查询中使用子查询返回的这个值来做一些计算。

SELECT S.[SecurityId], S.[Service], (select count(Id) ----joins and conditions---- where Id = S.[SecurityId]) as [Total]
FROM TableName S

现在在我的外部查询中,我想使用返回的 [Total] 值并进行更多计算,假设 [Total] + 100 AS [Summed]

如何访问外部查询中的子查询值?我不想一次又一次地执行子查询,想重用它第一次返回的值

这听起来像是横向连接:

SELECT s.[SecurityId], s.[Service], x.[Total], x.[Total] + 100 AS [Summed]
FROM TableName s
OUTER APPLY (
    SELECT count(Id) AS [Total]
    ---- joins and conditions---- 
    WHERE Id = S.[SecurityId]
) x

您可以按如下方式使用left join

SELECT S.[SecurityId], S.[Service], 
       t.[total] + 100 -- as per your requirement
  FROM TableName S
  LEFT JOIN (select id, count(Id) as [total]
             ----joins and conditions----
             group by Id) as T
    On s.[SecurityId] =  T.id