SQL根据条件添加值然后潜入两个总和

时间:2015-07-28 10:17:18

标签: sql ms-access

我有一个名为Data的表。

Data Year Type Value 1 1 5 1 1 10 1 2 15 1 2 25 1 1 15 1 2 20 1 1 5 2 2 10 2 2 45 2 2 10 2 1 20 2 2 5 2 1 15 2 1 0

我希望每年将所有类型1(sum1)的所有内容相加并且对类型2(sum2)的所有内容求和,然后将sum1除以sum2并将结果按年分组。对于第一年,sum1 =(5 + 10 + 15 + 5 = 35),sum2 =(15 + 25 + 20 = 60),sum1(35)/ sum(60)= 0.58333。完整的输出将是

Year Value 1 0.5833 2 0.5

我尝试了以下查询,但它不起作用。 SELECT d.Year, a.Sum1/b.Sum2 FROM Data d, (SELECT Data.Year, SUM(Value) AS Sum1 FROM Data WHERE Type=1 GROUP BY Data.Year) a, (SELECT Data.Year, SUM(Value) AS Sum2 FROM Data WHERE Type=2 GROUP BY Data.Year) b GROUP BY d.Year

当我运行查询时,我得到You tried to execute a query that does not include the specified expression 'a.Sum1/b.Sum2' as part of an aggregate function.我的查询中出错了什么?

1 个答案:

答案 0 :(得分:3)

您使用IIF功能

select Year,sum(iif(Type=1, value, 0))/sum(iif(Type=4, value, 0))
from data
GROUP BY Year