【问题标题】:Running Total in Ms-access query using SQL使用 SQL 在 Ms-access 查询中运行 Total
【发布时间】:2023-04-03 03:10:01
【问题描述】:

我想在我的一个访问查询中使用 SQL 计算运行总数(请不要使用 DSUM)。 我现有的查询中有 3 个字段,即 SubCategoryID、brand 和 Revenue,并且想计算每个 SubCategory 下的总收入。

我已经为它写了一个查询,但是有一些错误,我找不到纠正它的方法。

    SELECT   x.SubCategoryID
            ,x.brand
            ,x.[Avg Revenue]
              ( Select Sum(x2.[Avg Revenue]) 
                From FROM [BrandRevenue] x2
                Where x2.[SubCategoryID] = x.[SubCategoryID] AND x2.[Avg Revenue] <= x.[Avg Revenue]) As [Running Sum]
    FROM (Select SubCategoryID, brand, [Avg Revenue]
          FROM [BrandRevenue]
          Order BY SubCategoryID, [Avg Revenue] DESC) As x
    Group BY x.SubCategoryID, x.brand, x.[Avg Revenue];

感谢您的帮助:)

【问题讨论】:

  • 愿意分享错误是什么?
  • 查询表达式中的语法错误 'Select Sum(x2.[Avg Revenue]) From FROM [BrandRevenue(Weekly)] x2 Where x2.[SubCategoryID] = x.[SubCategoryID] AND x2.[Avg收入]

标签: sql ms-access


【解决方案1】:

您在相关子查询中重复了“发件人”:

  ( Select Sum(x2.[Avg Revenue]) 
    From FROM [BrandRevenue] x2
    ...

我认为您不需要 from 子句中的子查询或 GROUP BY。我认为这会更好,当然也更简单:

SELECT  x.SubCategoryID,
        x.brand,
        x.[Avg Revenue],
        (   SELECT  SUM(x2.[Avg Revenue]) 
            FROM    [BrandRevenue] x2
            WHERE   x2.[SubCategoryID] = x.[SubCategoryID] 
            AND     x2.[Avg Revenue] <= x.[Avg Revenue]
        ) AS [Running Sum]
FROM    BrandRevenue AS x
ORDER BY x.SubCategoryID, x.[Avg Revenue] DESC;

ADDENUM

我认为要解决品牌收入相同的问题,您需要在相关子查询中添加一些额外的逻辑:

SELECT  x.SubCategoryID,
        x.brand,
        x.[Avg Revenue],
        (   SELECT  SUM(x2.[Avg Revenue]) 
            FROM    [BrandRevenue] x2
            WHERE   x2.[SubCategoryID] = x.[SubCategoryID] 
            AND  (  x2.[Avg Revenue] <= x.[Avg Revenue]
                OR  (x2.[Avg Revenue] = x.[Avg Revenue] 
                AND x2.Brand <= x.Brand
                )
        ) AS [Running Sum]
FROM    BrandRevenue AS x
ORDER BY x.SubCategoryID, x.[Avg Revenue] DESC, x.Brand;

【讨论】:

  • 虽然有一个问题,当两个品牌的收入相同时,结果并不像预期的那样。知道如何解决这个问题吗?谢谢
  • 我已添加到答案中,希望能解决问题。
猜你喜欢
  • 2018-06-14
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2015-12-18
  • 2019-03-01
相关资源
最近更新 更多