在不同条件下查找Sql server中的列数

时间:2013-10-24 09:24:26

标签: sql-server-2008

下面的查询将为我提供每个库的发布计数

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

这是以增加两个JOINS为代价的,这个JOINS没有优化。

如何以更有效和优化的方式编写上述查询。

由于

1 个答案:

答案 0 :(得分: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