MSSQL子查询结果显示和计算

时间:2015-01-05 16:18:38

标签: sql-server subquery

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

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

4 个答案:

答案 0 :(得分:2)

为什么你不能这样做。将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 

答案 1 :(得分:2)

你可以使用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

答案 2 :(得分:1)

您还可以使用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

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

答案 3 :(得分:0)

尝试:

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