表名称产品,其中列由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。请帮助。
答案 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