我有一张桌子'书'。为简单起见,这里有3列:
name(text) | new(boolean) | press(text)
我需要选择拥有大多数新书的出版社(出版社)。 我不明白为什么Access显示“语法错误”。
SELECT press, COUNT(new) AS [Number of new books]
FROM books
WHERE new = TRUE
GROUP BY press
HAVING COUNT(new) =
SELECT MAX(s)
FROM
( SELECT COUNT(new) AS s, press
FROM books
WHERE new = TRUE
GROUP BY press
)
如果我只写第二部分:
SELECT MAX(s)
FROM
( SELECT COUNT(new) AS s, press
FROM books
WHERE new = TRUE
GROUP BY press
)
返回正确的值(5)
如果我只用条件= 5
写第一部分,那就很好。
SELECT press, COUNT(new) AS [Number of new books]
FROM books
WHERE new = TRUE
GROUP BY press
HAVING COUNT(new) = 5
我做错了什么?
答案 0 :(得分:7)
第二个查询应附有括号
SELECT press, COUNT(new) AS [Number of new books]
FROM books
WHERE new = TRUE
GROUP BY press
HAVING COUNT(new) =
(
SELECT MAX(s)
FROM
( SELECT COUNT(new) AS s, press
FROM books
WHERE new = TRUE
GROUP BY press
)
)
答案 1 :(得分:3)
您已经有一个汇总(GROUP BY
)查询,该查询会返回每press
个新书的数量。将其用作子查询,并按计数按降序排序后取TOP 1
行。
SELECT TOP 1
sub.press,
sub.CountOfNew AS [Number of new books]
FROM
(
SELECT
press,
COUNT(*) AS CountOfNew
FROM books
WHERE [new] = TRUE
GROUP BY press
) AS sub
ORDER BY sub.CountOfNew DESC
注意,如果多个press
es与最大[Number of new books]
相关联,则此查询将返回所有关联。 (但那么你的原始方法也是如此。)如果你只想要其中一个关系,请在ORDER BY
中包含一个唯一的字段(例如主键)。