gpt4 book ai didi

SQL计算2列的百分比

转载 作者:行者123 更新时间:2023-12-04 22:07:22 34 4
gpt4 key购买 nike

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

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

谢谢

最佳答案

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

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

关于SQL计算2列的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384093/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com