如下:
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 6select 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把多条语句合成一条是为了效率。

解决方案 »

  1.   

    急救:Count(*)...Group by不能返回count值为0的行 ===
    并不是这个问题
      

  2.   

    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 6select [count]=(select count(*) from @A where f1>B.f2), f2 from @B as B--result
    count       f2          
    ----------- ----------- 
    2           2
    1           4
    0           6(3 row(s) affected)
      

  3.   

    多谢这位好兄弟!真实的场景比这复杂,不如再进一步指教?
    比如条件改成 where (A.f1>B.f2 and A.f1<B.f3) // 多个参数B.f2、B.f3、B.f4
    并且要把count(*)=0 的B.f2、B.f3放进表C里,请问用您上面的写法怎么写?谢谢!
      

  4.   

    另外也还想知道,Group by中count为0的项就没办法返回了吗?呵呵
      

  5.   

    一般用having可以解决,可你这问题并非count的问题,而是SQL本身问题
      

  6.   

    @_@,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 6select * from @A A,@B B where (A.f1>B.f2)
    出來的結果:
    f1          f2          
    ----------- ----------- 
    3           2
    5           2
    5           4
      

  7.   

    要出來6的話,貌似是@B應該去left join @Aselect count(f1) as [count],f2  from @B b left join @A a on b.f2<a.f1 group by f2count       f2          
    ----------- ----------- 
    2           2
    1           4
    0           6
      

  8.   

    group by all B.f2
    即可