我正在使用MS Access执行以下任务(由于办公室限制)。我对SQL很新。
我想选择按街道,邮编和地点分组的所有商店。但是我只想将它们分组,如果SquareSum(在分组之后)<1000.Rue de gare 2应该分组,而Bahnhofstrasse 23应该是单独的线。
据我所知,MS Access不允许使用case语句。所以我的查询看起来像这样:
SELECT
Street,
ZIP,
Place,
Sum(Square) AS SumSquare,
FROM Table1
SWITCH (SumSquare > 1000, GROUP BY (Street, ZIP, Place))
我也尝试过:
GROUP BY
SWITCH (SumSquare > 1000, (Street, ZIP, Place))
但它一直告诉我,我有一个语法错误。有人可以帮帮我吗?
在Access中,我会使用多个查询来执行此操作。
如果您在行上有id(例如自动编号),这将更容易做到。
第一个查询标识应该求和的街道。
查询:SumTheseStreets
SELECT
Street,
ZIP,
Place,
Sum(Square) AS SumSquare
FROM Table1
GROUP BY Street, ZIP, Place
HAVING sum(Square) < 1000
请注意HAVING
有点像WHERE
条款,适用于GROUP BY
或SUM
之外
第二个查询标识其他行(下面的注释):
查询:StreetsNotSummed
SELECT
Street,
ZIP,
Place,
Square AS SumSquare
FROM Table1
LEFT JOIN SumTheseStreets ON Table1.Street = SumTheseStreets.Street AND Table1.ZIP = SUmTheseStreets.ZIP AND Table1.Place = SumTheseStreets.Place
WHERE SumTheseStreets.Street IS NULL;
几个笔记:
因此,此查询仅列出您不想要求的街道。
所以现在你需要第三个查询。这只包括这两个查询中的所有行。我不太确定这个上的Access语法,但如果这不对,那就有一个联合查询向导。
查询:TheAnswerRequired
SELECT
Street,
ZIP,
Place,
SumSquare
FROM SumTheseStreets
UNION
SELECT
Street,
ZIP,
Place,
SumSquare
FROM StreetsNotSummed
(它可能需要是UNION ALL
)
祝好运。
你可以使用UNION ALL
:
SELECT ts.*
FROM (SELECT Street, Zip, Place, SUM(Square) as SumSquare
FROM Table1
GROUP BY Street, Zip, Place
) as ts
WHERE ts.SumSquare < 1000
UNION ALL
SELECT t1.*
FROM Table1 as t1 INNER JOIN
(SELECT Street, Zip, Place, SUM(Square) as SumSquare
FROM Table1
GROUP BY Street, Zip, Place
) as ts
ON t1.Street = ts.Street AND t1.Zip = ts.Zip and t1.Place = ts.Place
WHERE ts.SumSquare >= 1000