无法在Access查询中生成运行总和

时间:2013-05-02 21:09:45

标签: sql ms-access

我一直试图让一个运行总和在Access查询中工作。 我一直在玩各种Dsum表达式,但它们都导致了错误。 基本上,我有两个列,一个有一年,一个有当年的部件数,我希望第三个是多年来部件数的运行总和。

前两列的我的SQL看起来像这样:

    SELECT DatePart("yyyy",[EoL]) AS AYear, Count(EquipmentQuery.Equipment) AS EquipCount
    FROM EquipmentQuery
    GROUP BY DatePart("yyyy",[EoL])
    ORDER BY DatePart("yyyy",[EoL]);

有关如何让第三列作为运行总和工作的任何建议? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

如果您创建报告,则会有property to calculate a running sum

如果您更喜欢查询,可以使用子查询来计算运行总和:

SELECT  DatePart("yyyy",[EoL]) AS AYear
,       Count(eq1.Equipment) AS EquipCount
,       (
        SELECT  Count(eq2.Equipment)
        FROM    EquipmentQuery eq2
        WHERE   DatePart("yyyy",eq2.[EoL]) <= DatePart("yyyy",eq1.[EoL])
        ) AS RunningSuma
FROM    EquipmentQuery AS eq1
GROUP BY 
        DatePart("yyyy",[EoL])
ORDER BY 
        DatePart("yyyy",[EoL]);

答案 1 :(得分:0)

尝试以下代码:

SELECT Year([EQ1].[EOL]) AS Yr, 
Sum(IIf(Year([EQ2].[eol])=Year([EQ1].[eol]),1,0)) AS [current], 
Sum(IIf(Year([EQ2].[eol])<=Year([EQ1].[eol]),1,0)) AS [cumulative]
FROM [equipmentquery] AS EQ1, [equipmentquery] AS [EQ2]
GROUP BY Year([EQ1].[EOL]);

如果您想要运行总计而不是计数:

SELECT Year([EQ1].[EOL]) AS Yr, 
Sum(IIf(Year([EQ2].[eol])=Year([EQ1].[eol]),[EQ2].equipment,0)) AS [current], 
Sum(IIf(Year([EQ2].[eol])<=Year([EQ1].[eol]),[EQ2].equipment,0)) AS [cumulative]
FROM [equipmentquery] AS EQ1, [equipmentquery] AS [EQ2]
GROUP BY Year([EQ1].[EOL]);