2014-03-06 29 views
0

我試圖平均過去3個完整驅動器的4列的結果。如果我沒有通過FromDateTime desc訂購,我會獲得該帳戶的最早驅動器。這不是我所需要的。按順序使用AVG

但是當我嘗試拉的平均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

*從您的問題的編輯*您不能通過查詢沒有返回的東西命令。按日期時間分組,然後您可以通過它訂購。 – Bobby

回答

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