尝试使用别名Transact Sql时出现无效的列名错误

时间:2016-12-14 16:00:38

标签: sql tsql subquery

我打算做的是有一个剩余订单列,这将是以下计算的结果: [orderedvalue] - [totaljobvalue]

select [orderedvalue] = sum([ordervalue]), 
       jobtype,
       [totaljobvalue] = (select sum([total value]) 
                          from job 
                          where jobType = quotetrackerorders.jobType 
                          and reference like '%40330%')
from quotetrackerorders
where quoteref like '%40330%'
group by jobtype

我尝试过以下代码:

select [orderedvalue] = sum([ordervalue]), 
       jobtype,
       [totaljobvalue] = (select sum([total value]) 
                          from job 
                          where jobType = quotetrackerorders.jobType 
                          and reference like '%40330%'),
       [orderremaining] = [orderedvalue] - [totaljobvalue]
from quotetrackerorders
where quoteref like '%40330%'
group by jobtype

但是这不起作用,因为它不会将任何别名识别为列...我该怎么做才能实现以下结果:

  • JobType =壁画
  • Orderedvalue = 311654(示例值)
  • TotalJobvalue = 3446(示例值)
  • OrderRemaining = 64654(示例值)

您知道如何让SQL将这些别名识别为列吗?

1 个答案:

答案 0 :(得分:2)

考虑以下

Select A.*
      ,SomeName = [orderedvalue] - [totaljobvalue]
 From (
        Select [orderedvalue] = sum([ordervalue])
              , jobtype
              , [totaljobvalue] = (select sum([total value]) 
                                   from job 
                                   where jobType = quotetrackerorders.jobType 
                                   and reference like '%40330%')
        from quotetrackerorders
        where quoteref like '%40330%'
        group by jobtype
) A