SQL计算2列的百分比

时间:2013-08-22 15:00:04

标签: sql sql-server tsql

我有问题,我需要计算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)

任何帮助都会非常感激,因为我不确定从哪里开始!

由于

1 个答案:

答案 0 :(得分:1)

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

select CountOfPlannedVisits, 
       CountOfPlannedVisitsClosed, 
       100 * CountOfPlannedVisits / CountOfPlannedVisitsClosed, ...
from (
  select some_expression as CountOfPlannedVisits ,
  some_other_expression as CountOfPlannedVisitsClosed
  ....
) a_table
....