UglySwede
UglySwede

Reputation: 459

How do I use a previous calculation in a SELECT in SQL Server?

I've worked a bit with MS Access, but I'm no expert on SQL Server. And now I've found a difference that puzzles me. (I'm using SQL Server 2008.)

I'm doing some calculations in a SELECT, and want to use the result from one calculation in the next one.

Let's say we have a table Products with two fields - Name and Price. In MS Access, this query works fine:

  SELECT Name, Price * 2 AS DoublePrice, DoublePrice * 2 AS QuadPrice
  FROM Products

I.e. I use the result of the first calculation in the next. This gives the result I expect - name + double the price + four times the price.

But this won't compile under SQL Server - I get an "unknown field: DoublePrice"-error in the second calculation.

Is there any way to make this work? I.e. to use a (named) calculation later in the same SELECT? I do some pretty large calculations and want to build on those values in other calculations. And it feels stupid to add an extra view/sub-SELECT just for that...

Grateful for any help! :-)

Upvotes: 1

Views: 130

Answers (1)

Lamak
Lamak

Reputation: 70658

Nope, not directly. Either you use a derived table, a CTE, a CROSS APPLY or even the calculation all over again:

-- derived table
SELECT *, DoublePrice * 2 AS QuadPrice
FROM (  SELECT Name, Price * 2 AS DoublePrice
        FROM Products) P

-- CTE
;WITH CTE AS
(
    SELECT Name, Price * 2 AS DoublePrice
    FROM Products
)
SELECT *, DoublePrice * 2 AS QuadPrice
FROM CTE

-- Just do the calculation again
SELECT Name, Price * 2 AS DoublePrice, (Price * 2) * 2 AS QuadPrice
FROM CTE

-- CROSS APPLY
SELECT *, 2 * DoublePrice AS QuadPrice
FROM Products P
CROSS APPLY (SELECT 2 * Price) AS T(DoublePrice)

Upvotes: 1

Related Questions