【问题标题】:SQL Server - Reuse the value returned by the subquery without executing the subquery againSQL Server - 重用子查询返回的值而不再次执行子查询
【发布时间】:2021-03-26 06:17:36
【问题描述】:

我在我的选择查询中使用了一个子查询,它给了我一个聚合值,子查询有 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]

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

【问题讨论】:

  • “我不想一次又一次地执行子查询”——仅仅因为同一个子查询在一个查询中多次出现在文本中,那 not 是否意味着服务器必然多次执行。在 SQL 中,你告诉系统你想要什么,而不是如何去做

标签: sql sql-server subquery lateral-join


【解决方案1】:

这听起来像是横向连接:

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

【讨论】:

    【解决方案2】:

    您可以按如下方式使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      相关资源
      最近更新 更多