读书人

急救:Count(*).Group by不能返回coun

发布时间: 2011-12-31 23:50:30 作者: rapoo

急救:Count(*)...Group by不能返回count值为0的行
如下:
declare @A table(f1 int)
declare @B table(f2 int)

insert @A select 1 union all select 3 union all select 5
insert @B select 2 union all select 4 union all select 6

select count(*),B.f2 from @A A,@B B where (A.f1> B.f2) group by B.f2

本来设想返回的结果是
count B.f2
---------------------
2 2
1 4
0 6

谁知在SQL SERVER 2000里只返回前两行,最后一行那个count=0的项没了,而这一项恰恰是我所关心的。谁知道该怎么取到这一项?是否可以象set statistics time on那样打开某个开关以取到这一项,或者改写一下句子以获得想要的B.f2=2这一项?

注:这是简化后的模型,真实的应用场景里是不允许修改(A.f1> B.f2)这个条件的,即把(A.f1> XXX)整个看成一个判断条件,用B.f2一个个去取代XXX,条件不成立的B.f2就是我想要的,即
select count(*) from A where (A.f1> 2)
select count(*) from A where (A.f1> 4)
select count(*) from A where (A.f1> 6)
最后一行count=0的那个6就是我想要的。之所以用group把多条语句合成一条是为了效率。

[解决办法]
急救:Count(*)...Group by不能返回count值为0的行

===
并不是这个问题
[解决办法]
一般用having可以解决,可你这问题并非count的问题,而是SQL本身问题
[解决办法]
@_@,LZ的SQL就有找出6一,以你的例子可以行
declare @A table(f1 int)
declare @B table(f2 int)

insert @A select 1 union all select 3 union all select 5
insert @B select 2 union all select 4 union all select 6

select * from @A A,@B B where (A.f1> B.f2)
出的果:
f1 f2
----------- -----------
3 2
5 2
5 4
[解决办法]
group by all B.f2
即可
[解决办法]
学习

读书人网 >SQL Server

热点推荐