Omega
Omega

Reputation: 113

How to use a calculated column to calculate another column in the same query using a subquery

I'm trying to add a new calculated field (TravelTime) based on the NLength and NSpeedLimit fields from the following query

SELECT          
        sc.OBJECTID, 
        sn.Name, 
        case    when hn.side = 'Right Side' then ''
            else sc.LCity
        end as LCity, 
        case    when hn.side = 'Left Side' then ''
            else sc.RCity
        end as RCity, 
        case    when hn.side = 'Right Side' then ''
            else sc.LZip
        end as LZip, 
        case    when hn.side = 'Left Side' then ''
            else sc.RZip
        end as RZip, 
        sc.SHAPE.STLength() AS NLength,
        ISNULL(sc.SpeedLimit,1) AS NSpeedLimit

FROM            STREETNAME AS sn 
    INNER JOIN
                STREETHASSTREETNAME AS hn ON 
                         sn.GlobalID = hn.GlobalID AND 
                         hn.Role = 'Primary'
INNER JOIN      STREETCENTERLINE AS sc ON 
                hn.GlobalID = sc.GlobalID

The new calculated field is TravelTime = NLength/(NSpeedLimit*88) but I can't add NLength/(NSpeedLimit*88) AS TravelTimein the select statement. I know I need to do a subquery but I don't know where it's supposed to go.

Upvotes: 1

Views: 1389

Answers (2)

Gudwlk
Gudwlk

Reputation: 1157

You can use Temp_tables, Derived tables or Common table expressions (CTE) to obtain the result. Simple approach would be Derived table as you dont need much more coding.

  SELECT A.*
  ,  A.NLength/(A.NSpeedLimit * 88)  as [TravelTime]
  FROM
  (


  SELECT          
    sc.OBJECTID, 
    sn.Name, 
    case    when hn.side = 'Right Side' then ''
        else sc.LCity
    end as LCity, 
    case    when hn.side = 'Left Side' then ''
        else sc.RCity
    end as RCity, 
    case    when hn.side = 'Right Side' then ''
        else sc.LZip
    end as LZip, 
    case    when hn.side = 'Left Side' then ''
        else sc.RZip
    end as RZip, 
    sc.SHAPE.STLength() AS NLength,
    ISNULL(sc.SpeedLimit,1) AS NSpeedLimit

  FROM    STREETNAME AS sn 
   INNER JOIN
            STREETHASSTREETNAME AS hn ON 
                     sn.GlobalID = hn.GlobalID AND 
                     hn.Role = 'Primary'
          INNER JOIN      STREETCENTERLINE AS sc ON 
              hn.GlobalID = sc.GlobalID

            ) AS A

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1271231

You can add the columns in the FROM clause using apply:

SELECT . . .
       v.NLength, v.NSpeedLimit, 
        (v.NLength / (v.NSpeedLimit*88)) as TravelTime
FROM STREETNAME sn JOIN
     STREETHASSTREETNAME hn
     ON sn.GlobalID = hn.GlobalID AND 
        hn.Role = 'Primary' JOIN
     STREETCENTERLINE sc
     ON hn.GlobalID = sc.GlobalID CROSS APPLY
     (VALUES (sc.SHAPE.STLength(), COALESCE(sc.SpeedLimit, 1)
     ) v(NLength, NSpeedLimit)

Upvotes: 0

Related Questions