3

我有一张桌子“书”。为简单起见,这里有 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

我究竟做错了什么?

4

2 回答 2

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
  )
)
于 2012-09-06T00:06:29.813 回答
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

注意,如果多个presses 被绑定到 maximum [Number of new books],这个查询将返回所有的关系。(但您的原始方法也是如此。)如果您只想要其中一个关系,请在ORDER BY.

于 2012-09-06T01:05:53.610 回答