简体   繁体   中英

Running Total in Ms-access query using SQL

I want to calculate running total in one of my access queries using SQL ( no DSUM please). I have 3 fields in my existing query Namely SubCategoryID, brand and Revenue and would like to calculate the running total of the revenue under each SubCategory.

I've written a query for it, but there is some error and I cant find a way to correct it.

    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];

Thanks for helping :)

You have repeated "From" in your correlated subquery:

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

I don't think you need the subquery in the from clause, or the GROUP BY either. I think this will be better, and certainly simpler:

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

I think to get around the problem of Brands having the same revenue you will need to add some additional logic to your correlated subquery:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM