SQL Count()和GROUP BY

时间:2012-12-07 14:40:43

标签: sql

我遇到(简单)SQL查询的问题。

背景是,每个Book都有一个(或多个)定义BookLanguages

该查询返回9本书,这是好的。

SELECT b.BookID
FROM Book b
JOIN BookLanguages bls ON b.BookID = bls.BookID
WHERE b.IsActive= 1 
       AND
        bls.BookLanguageID = 25
GROUP BY b.BookID

但是,我必须拥有符合该标准的总书数(用于分页目的)。

如果我只是运行该查询

SELECT COUNT(b.BookID)
FROM Book b
JOIN BookLanguages bls ON b.BookID = bls.BookID
WHERE b.IsActive= 1 
       AND
        bls.BookLanguageID = 25
GROUP BY b.BookID

我得到了9行的1值(这是语言计数,因为当我删除AND bls.BookLanguageID = 25条件时,我得到9行,值为1或2 - 因为有些书籍定义了2种语言)

那么,重点是 - 如何获得9数而不是9行?

2 个答案:

答案 0 :(得分:3)

删除群组
Select
  Count(*)
From
  Book b
    Inner Join
  BookLanguages bls 
    On b.BookID = bls.BookID
Where
  b.IsActive= 1 And
  bls.BookLanguageID = 25

答案 1 :(得分:2)

尝试DISTINCT而不是GROUP BY

SELECT COUNT(DISTINCT b.BookID)
FROM Book b
JOIN BookLanguages bls ON b.BookID = bls.BookID
WHERE b.IsActive= 1 
       AND
        bls.BookLanguageID = 25

GROUPING BY Id为Id的每个值返回一行,因此在您的情况下为9行。