我有一个查询,我需要获得使用子查询生成的列的平均值。 我的问题:
Insert Into #TEMPTABLE
SELECT
[BU] =(SELECT BusinessUnit_Name FROM mBusinessUnit WHERE BusinessUnit_ID = ra.BusinessUnit_ID ),
[Division] = (SELECT Division_Name FROM mDivision WHERE Division_ID = ra.Division_ID),
[Product] = (SELECT Product_Name FROM mProduct WHERE Product_ID = ra.Product_ID),
[Resource_ID] = ra.Resource_ID,
[Allocation_Percentage] = ra.Resource_Allocation_Percentage,
[NoOfMonths] = @noOfMonths,
[Effective days] = (Select d.Division_No_Days from mDivision d where d.Division_ID = ra.Division_ID) / @noOfMonths,
[Efficiency_Percentage] = (((Select d.Division_No_Days from mDivision d where d.Division_ID = ra.Division_ID) / @noOfMonths) * ra.Resource_Allocation_Percentage) / 100,
[AVG_Efficiency] = AVG ((((Select d.Division_No_Days from mDivision d where d.Division_ID = ra.Division_ID) / @noOfMonths) * ra.Resource_Allocation_Percentage) / 100)
FROM mResourceAllocation ra
WHERE
BusinessUnit_ID = @businessUnitId AND Division_ID = ra.Division_ID AND Product_ID = ra.Product_ID AND
Resource_Allocation_From_Date <= @firstDayOfFromDate AND Resource_Until_Date >= @lastDayOfFromDate
GROUP BY
ra.BusinessUnit_ID,
ra.Division_ID,
ra.Product_ID,
ra.Resource_ID,
Resource_Allocation_Percentage
我希望[Efficiency_Percentage]
列中的[AVG_Efficiency]
平均值。
请帮忙
我需要在一个变量或具有相同值的列中平均整个表列[Efficiency_Percentage]
。
答案 0 :(得分:0)
如果我没有记错,您不需要任何GROUP BY
,因为您只是主要显示非聚合的mResourceAllocation记录。您需要获得所有结果行的平均值是AVG
的分析版本,即AVG() OVER()
。
应该是这样:
SELECT
bu.BusinessUnit_Name AS [BU],
d.Division_Name AS [Division],
p.Product_Name AS [Product],
ra.Resource_ID AS [Resource_ID],
ra.Resource_Allocation_Percentage AS [Allocation_Percentage],
@noOfMonths AS [NoOfMonths],
d.Division_No_Days / @noOfMonths AS [Effective days],
d.Division_No_Days / @noOfMonths * ra.Resource_Allocation_Percentage / 100
AS [Efficiency_Percentage],
AVG(d.Division_No_Days / @noOfMonths * ra.Resource_Allocation_Percentage / 100) OVER ()
AS [AVG_Efficiency]
FROM mResourceAllocation ra
JOIN mDivision d USING (Division_ID)
JOIN mBusinessUnit bu USING (BusinessUnit_ID)
JOIN mProduct p USING (Product_ID)
WHERE ra.BusinessUnit_ID = @businessUnitId
AND ra.Resource_Allocation_From_Date <= @firstDayOfFromDate
AND ra.Resource_Until_Date >= @lastDayOfFromDate;