我想使用SQL计算我的一个访问查询中的运行总计(请不要DSUM)。 我现有的查询中有3个字段,即SubCategoryID,品牌和收入,并希望计算每个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];
感谢您的帮助:)
答案 0 :(得分:1)
你已经重复了#34;来自&#34;在您的相关子查询中:
( 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 强>
我认为要解决Brands具有相同收入的问题,您需要为相关子查询添加一些额外的逻辑:
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;