SELECT不返回数值

时间:2012-09-06 00:05:03

标签: sql ms-access select group-by

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

我做错了什么?

2 个答案:

答案 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中包含一个唯一的字段(例如主键)。