3

我有一个问题,我需要计算 2 个不同列之间的百分比。不幸的是,我无法让它工作,当我运行它时,我得到的只是“无效的列名'CountOfPlannedVisits'”和“无效的列名'CountOfPlannedVisitsClosed'”

SELECT       Count(*) As CountOfPlannedVisits, MAX(datename(month, dbo.tblVisit.DateConfirmed)) AS MonthName,
    SUM(CASE WHEN tblVisit.VisitTypeRef <> '5' THEN 1 ELSE 0 END) AS CountOfPlannedVisitsClosed, CAST(100.0 * SUM("CountOfPlannedVisits") / SUM(CountOfPlannedVisitsClosed) AS Decimal(5,2) ) As OverallAttendance
FROM            dbo.tblContract INNER JOIN
                         dbo.tblCustomer ON dbo.tblContract.CustomerRef = dbo.tblCustomer.CustomerID INNER JOIN
                         dbo.tblContractSite ON dbo.tblContract.ContractID = dbo.tblContractSite.ContractRef INNER JOIN
                         dbo.tblVisit ON dbo.tblContractSite.CardNumber = dbo.tblVisit.CardNumber
WHERE        (tblCustomer.CustomerNumber = '08434') 
AND (tblVisit.Routine = '1')
AND year(tblVisit.DateConfirmed) = Year('2013')--@DateYear)
AND  dbo.IsOnHoldEx(tblContract.OnHold, tblContractSite.OnHold, tblContract.OnHoldStartDate, tblContract.OnHoldEndDate, tblContractSite.OnHoldStartDate, tblContractSite.OnHoldEndDate) = 0  
AND tblVisit.Deleted = 0 -- make sure we dont pull through deleted visits
AND (tblContractSite.DateInactive is NULL or tblContractSite.DateInactive > GetDate()) 
GROUP BY  month(dbo.tblVisit.DateConfirmed)

任何帮助将不胜感激,因为我不确定从这里去哪里!

谢谢

4

1 回答 1

1

您只能在子句中引用列别名(如CountOfPlannedVisits您的情况) 。order by在其他任何地方,您必须重复表达式或使用子查询表,例如:

select CountOfPlannedVisits, 
       CountOfPlannedVisitsClosed, 
       100 * CountOfPlannedVisits / CountOfPlannedVisitsClosed, ...
from (
  select some_expression as CountOfPlannedVisits ,
  some_other_expression as CountOfPlannedVisitsClosed
  ....
) a_table
....
于 2013-08-22T15:07:08.670 回答