我试图在Access中使用SQL获取查询,其中:
1)我过滤掉没有销售的水果
2)我将不同水果的销售额相加,并在每一行显示结果。
我使用下面的代码,但它并不接近我想要的东西,因为我也想要水果N°没有销售的水果销售。
SELECT MySheet.Fruit, MySheet.[Fruit N°], SUM(Sales)
FROM MySheet
GROUP BY Fruit, [Fruit N°]
HAVING SUM(Sales) > 0;
任何想法如何纠正我的代码以达到我的两点1)和2)?
答案 0 :(得分:2)
SELECT
MySheet.Fruit, MySheet.[Fruit N°], summary.totalSales
FROM
MySheet
INNER JOIN
(
SELECT Fruit, SUM(Sales) AS totalSales
FROM MySheet
GROUP BY Fruit
)
summary
ON summary.Fruit = MySheet.Fruit
WHERE
summary.totalSales > 0
答案 1 :(得分:1)
您想要subquery
:
SELECT S.Fruit, S.[Fruit N°],
(SELECT SUM(Sales)
FROM MySheet S1
WHERE S1.Fruit = S.Fruit
) TotalSales
FROM MySheet S
WHERE EXISTS (SELECT 1
FROM MySheet
WHERE Fruit = S.Fruit
HAVING SUM(Sales) > 0
);
答案 2 :(得分:1)
您可以使用子查询为您进行分组:
SELECT
MySheet.Fruit,
MySheet.[Fruit N°],
s.FruitSales
FROM MySheet m
INNER JOIN (
SELECT
Fruit,
SUM(Sales) AS FruitSales
FROM MySheet
GROUP BY Fruit
HAVING SUM(Sales) > 0
) s
ON m.Fruit = s.Fruit