2013-08-22 316 views
3

我有一個問題,我需要計算2個不同列之間的百分比。不幸的是,我不能讓它的工作,當我運行此我得到的是「無效的列名稱CountOfPlannedVisits'」 &「無效的列名稱CountOfPlannedVisitsClosed'」SQL計算2列的百分比

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')[email protected]) 
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) 

任何幫助將不勝感激,因爲我我不確定該從哪裏出發!

感謝

+0

您可以更新查詢,以顯示它的所有現在?:你有一個'WHERE'與後一無所獲。 –

回答

1

您只能在order by子句中引用列別名(如你的情況CountOfPlannedVisits)。其他任何地方,你必須重複的表達或使用子查詢表,是這樣的:

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