0

下面的查询会给我每个图书馆的出版数量

Select lib.Name, COUNT(pub.Id) From Library lib
INNER JOIN Publication lib.ID = pub.FK_Library_Id

但是,在出版物表中,我有免费出版物和付费出版物,我也想要付费出版物和免费出版物的数量。

下面的查询给了我结果

Select lib.Name, COUNT(pub.Id), COUNT(pub1.Id) as 'Paid Publication COunt', 
COUNT(pub2.Id) as 'FreePublication COunt'
 From Library lib
INNER JOIN Publication pub ON lib.ID = pub.FK_Library_Id
LEFT JOIN Publication pub1 ON lib.ID = pub1.FK_Library_Id and pub1.Price > 0
LEFT JOIN Publication pub2 ON lib.ID = pub2.FK_Library_Id and pub2.Price =0

但是,这是以增加两个未优化的连接为代价的。

我怎样才能以更有效和优化的方式编写上述查询。

谢谢

4

1 回答 1

1

您也许可以将 SUM 与 CASE 语句一起使用,如下所示:

Select lib.Name, COUNT(*),
SUM(CASE WHEN pub.Price > 0 THEN 1 ELSE 0 END) as 'Paid Publication COunt', 
SUM(CASE WHEN pub.Price = 0 THEN 1 ELSE 0 END) as 'FreePublication COunt'
 From Library lib
INNER JOIN Publication pub ON lib.ID = pub.FK_Library_Id
Group By lib.Name
于 2013-10-24T09:42:34.573 回答