如何使用计算列来计算使用子查询的同一查询中的另一列

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

我正在尝试根据以下查询中的 NLength 和 NSpeedLimit 字段添加新的计算字段 (TravelTime)

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

新的计算字段为TravelTime = NLength/(NSpeedLimit*88) 但我无法在 select 语句中添加 NLength/(NSpeedLimit*88) AS TravelTime。我知道我需要做一个子查询,但我不知道它应该去哪里。

您可以使用 apply:

FROM 子句中添加列
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)

您可以使用 Temp_tables、派生 table 或通用 table 表达式 (CTE) 来获取结果。将派生出简单的方法 table,因为您不需要更多编码。

  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