Display subquery result and use it for calculation

Asked

Viewed 144 times

3

I need to present a result of a subquery and use the same result to perform a calculation, is it possible to play it for a variable in MS SQL 2008 or something like that? example:

SELECT
    @test = (SELECT COUNT(*) FROM [tableTest] WHERE [tableTest].[columnA] = [tableA].[columnA]) as 'Counter'
    , (@test * 50) as 'Calc'
    , [tableA].[columnA]
FROM tableA
  • My question has been answered in the English version:&#xD; <http://stackoverflow.com/questions/27783554/mssql-subquery-result-to-show-and-calculate/>

  • And received a similar reply in Portuguese too! : D

1 answer

4


You can use a TEC (Common Table Expression)

WITH CounterTable(columnA, Counter) AS
( 
    SELECT [tableTest].[columnA], COUNT(*) FROM [tableTest] 
    WHERE [tableTest].[columnA] = [tableA].[columnA]
) 
SELECT Counter, columnA, Counter * 50 AS Calc
FROM CounterTable;

Use a INNER JOIN can make your query more readable

WITH CounterTable(columnA, Counter) AS
( 
    SELECT [tableTest].[columnA], COUNT(*) 
    FROM [tableTest] 
    INNER JOIN [tableA] ON [tableTest].[columnA] = [tableA].[columnA]
) 
SELECT Counter, columnA, Counter * 50 AS Calc
FROM CounterTable;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.