我在MS Access中有表格,其中包含年份,期间(仅1
和2
的值),Costs_Per_Capita和CALCULATED_Period_Avg_Costs,PK是ID。
我需要计算CALCULATED_Period_Avg_Costs
。它应该从Costs_Per_Capita
列返回指定时间段内Period
的平均值。在Excel中,我使用SUMIF / COUNTIF执行此操作,返回平均IF。
您是否有一些建议如何在SQL中编写代码来执行此操作?
结果应该如下:
Costs_Per_Capita Period CALCULATED_Period_Avg_Costs
15,505 1 15976.27582
16,368 1 15976.27582
16,037 1 15976.27582
15,995 1 15976.27582
15,000 2 16000
17,000 2 16000
我用过声明:
SELECT
Costs_Per_Capita, Period
IFF (Period = 1,
(Select AVG(Costs_Per_Capita) From Costs Where Period = 1),
(Select AVG(Costs_Per_Capita) From Costs Where Period = 2)
AS result
FROM Costs;
在查询表达式中仍然出现“语法错误(缺少运算符)......”
答案 0 :(得分:0)
我想我知道你要求的是什么,我相信这就是你要找的东西 -
Select
Costs_Per_Capita,
Related_Period_ID,
(Select
Case when Related_Period_ID = 1 then
(Select
AVG(Costs_Per_Capita)
From Costs_Per_Capita_Table
Where Related_Period_ID = 1)
else
(Select
AVG(Costs_Per_Capita)
From Costs_Per_Capita_Table
Where Related_Period_ID = 2)
END
)
From
Costs_Per_Capita_Table
将CASE更改为IFF
Select
IFF (Related_Period_ID = 1,
(Select
AVG(Costs_Per_Capita)
From Costs_Per_Capita_Table
Where Related_Period_ID = 1),
(Select
AVG(Costs_Per_Capita)
From Costs_Per_Capita_Table
Where Related_Period_ID = 2)
答案 1 :(得分:0)
我这样做: SELECT Costs.Costs_Per_Capita,Costs.Period,
IIF(Costs.Period = 1,
(从期间= 1的成本中选择AVG(Costs_Per_Capita)),
(从期间= 2的成本中选择AVG(Costs_Per_Capita))
AS结果
FROM Costs;
其他方式,如果更多句点apper正在使用子查询,那就更好了:
SELECT Costs.Period,Costs.Costs_Per_Capita,tmpQry.CALCULATED_Period_Avg_Costs
FROM OF INES JOIN(SELECT Costs.Period,Avg(Costs.Costs_Per_Capita)
AS CALCULATED_Period_Avg_Costs FROM Costs
GROUP BY Costs.Period)AS tmpQry ON Costs.Period = tmpQry.Period;
也许有人会在以后使用它...
答案 2 :(得分:0)
Select CostsPerCapital, Period, avg(CostPerCapita) over (partition by Period)
From Table
Where....
Order by ...