如何在SQL-2中显示和计数多个列

时间:2014-10-22 22:30:18

标签: sql sql-server sql-server-2008 tsql

表名称产品,其中列由Apple(A)和Grape(G)组成。

A G

1 1    
1 1
1 Null

我运行了查询..

Select count(Apple) as 'Apple' count(Grape) as 'Grape' 
from products 
where Apple = 1 and Grape = 1

我从上述查询得到的输出是

Apple=2
Grape=2

我应该得到Apple = 3和Grape = 2。请帮助。

3 个答案:

答案 0 :(得分:1)

如果您需要总数,这似乎更安全。它更安全地处理空值,并且不依赖于聚合默认处理空值的不同行为,这可能会使某些查询失效。

SELECT SUM(ISNULL(Apple,0)) AS Apple, SUM(ISNULL(Grapes,0)) AS Grape FROM Products

答案 1 :(得分:0)

您的where条件仅包含行where Apple = 1 and Grape = 1 因此忽略grape NULL的完整行。

答案 2 :(得分:0)

create table AppleGrape(A int, B int)

go
insert into AppleGrape values(1,1)
insert into AppleGrape values(1,1)
insert into AppleGrape values(1,NULL)

SELECT sum(A) as 'Apple',sum(isnull(B,0)) as 'Grape'
FROM AppleGrape

检查小提琴。 http://sqlfiddle.com/#!3/126e05/5