fa fb
1 2
3 2
2 3
1 3用select fb, count(fb) as fbcount from table1 group by fb 的结果为fb fbcount
2 2
3 2但我希望得出以下结果:fb fbcount
2 2
3 1因为第4条记录的 fa为1已经出现过了, 不希望它再被统计到

解决方案 »

  1.   

    还有象这个SELECT left(ua, (iif PATINDEX('%/%', ua) = 0 ? len(ua) : PATINDEX('%/%', ua)) )
      FROM users因为不能用iif 应该怎么写法呢
      

  2.   

    1、为什么不是1 2被去掉而是13倍去掉,排序规则是什么?记录是没有先后之分的。
    换个提法保留fb数值最小的fa进行计数是否合理?
    2、case
      

  3.   

    /*第二个问题:iif(?:)*/
    select left(ua,case when patindex('%/%',ua) = 0 then len(ua) else patindex('%/%',ua) end)
    from users/*第一个问题(测试数据该动了一下,楼主的例子数据好像有矛盾)*/
    ----创建测试数据
    declare @t table(fa int,fb int)
    insert @t
    select 11 , 3 union all
    select 31 , 2 union all
    select 21 , 2 union all
    select 11 , 3 union all
    select 11 , 4
    ----方法一:效率较高
    select fb,count(fb) as fbcount from
    (
    select fb,fa from @t group by fb,fa
    ) b group by fb----方法二:效率最差
    --生成唯一ID
    if object_id('tempdb..#tmp') is not null
          drop table #tmp
    select id = identity(int,1,1),* into #tmp from @t
    --汇总计数
    select fb,count(fb) as fbcount from 
    (
    select * from #tmp a 
    where not exists(select 1 from #tmp where fa = a.fa and fb = a.fb and id < a.id)
    ) as b
    group by fbdrop table #tmp
      

  4.   

    fa fb
    1 2
    3 2
    2 3
    1 3
    --测试代码
    declare @t table(fa int,fb int)
    insert @t
    select 1 ,2
    union all
    select 3, 2
    union all
    select 2, 3
    union all
    select 1, 3
    --查询语法:
    select fb,count(fa) from 
    (select fa,min(fb) as fb from @t group by fa)a
    group by fb
    --结果
    fb                      
    ----------- ----------- 
    2           2
    3           1(所影响的行数为 2 行)