我正在尝试平均过去3个已完成驱动器的4列结果。如果我不按FromDateTime desc订购,我会获得该帐户的最早驱动器。这不是我需要的。
但是当我尝试拉出4列的平均值时,我收到此消息: “rpt_DriveMaster.FromDateTime”列在ORDER BY子句中无效,因为它不包含在聚合函数或GROUP BY子句中。
有人可以帮我理解如何正确编写此查询吗?我应该查看子查询吗?只是不确定。
SELECT top 3
AVG(ProcedureProjection),
AVG(ProceduresPerformed),
AVG(DPaCT.ProductProjection),
AVG(DPaCT.ProductsCollected)
/*DM.DriveID, DM.FromDateTime, DM.AccountID, Acct.Name, DPaCT.ProcedureProjection,
DPaCT.ProductProjection, DPaCT.ProceduresPerformed, DPaCT.ProductsCollected*/
FROM rpt_DriveMaster DM
INNER JOIN DriveProjectionandCollectedTotals DPaCT ON DM.DriveID = DPaCT.DriveID
INNER JOIN rpt_Accounts Acct ON DM.AccountID = Acct.AccountID
where Acct.accountid='17845' and DM.fromdatetime < '2014-04-01' and DM.StatusID='2'
Order by DM.FromDateTime;
答案 0 :(得分:0)
top 3
表示您最多会返回当前结果的3行。如果您需要计算3行的平均值,首先需要对它们进行过滤。我会使用子查询:
SELECT
AVG(ProcedureProjection),
AVG(ProceduresPerformed),
AVG(DPaCT.ProductProjection),
AVG(DPaCT.ProductsCollected)
FROM
(
SELECT TOP 3 ProcedureProjection, ProceduresPerformed, DPaCT.ProductProjection, DPaCT.ProductsCollected
FROM rpt_DriveMaster DM
INNER JOIN DriveProjectionandCollectedTotals DPaCT ON DM.DriveID = DPaCT.DriveID
INNER JOIN rpt_Accounts Acct ON DM.AccountID = Acct.AccountID
where Acct.accountid='17845' and DM.fromdatetime < '2014-04-01' and DM.StatusID='2'
) as a