MSSQL 子查询结果显示和计算

MSSQL subquery result to show and calculate

我需要显示子查询结果并使用相同的结果计算其他值,是否可以在 MS SQL 2008 或类似的变量中将此值设置为变量? 例子:

SELECT
    @test = (SELECT COUNT(*) FROM [tableTest] WHERE [tableTest].[columnA] = [tableA].[columnA]) as 'Counter'
    , (@test * 50) as 'Calc'
    , [tableA].[columnA]
FROM tableA

你为什么不能这样做。将 subquery 移到 select 语句之外,并将结果存储在 variable

然后使用该变量进行计算。

declare @test int = (SELECT COUNT(*) FROM [tableTest]) 

SELECT
    @test as 'Counter'
    , (@test * 50) as 'Calc'
    , [tableA].[columnA]
FROM tableA

更新:

SELECT [Counter],
       ( [Counter] * 50 ) AS 'Calc',
       columnA
FROM   (SELECT (SELECT Count(*)
                FROM   [tableTest]
                WHERE  [tableTest].[columnA] = [tableA].[columnA]) AS 'Counter',
               [tableA].[columnA]
        FROM   tableA) A 

您可以使用 cte 并加入它。

with cte as (select count(*) cnt, columnA from [tableTest] group by columnA)
select 
   c.cnt as 'Counter',
   c.cnt * 50 as 'Calc',
   a.columnA
from tableA a
join cte c on c.columnA = a.columnA

当然也可以用子查询来完成

select 
  a.columnA,
  c.cnt as 'Counter',
  c.cnt * 50 as 'Calc'
from tableA a
join (select columnA, count(*) as cnt
      from tableTest
      group by columnA) c
  on c.columnA = a.columnA

尝试:

SELECT  t2.[Count]
       ,t2.[Count] * 50 As [Calc]
       ,[tableA].[columnA]
FROM TableA 
CROSS APPLY
(
   SELECT COUNT(*) AS [Count] 
   FROM TableTest
   WHERE [tableTest].[columnA] = [tableA].[columnA]
) t2

你也可以使用correlated sub-queries:

SELECT 
   Counter = (SELECT COUNT(*) FROM tableTest t WHERE t.columnA = a.columnA),
   Calc    = (SELECT COUNT(*) FROM tableTest t WHERE t.columnA = a.columnA) * 50,
   a.columnA
FROM tableA a

它将被优化为只评估一次。