去掉重复之后分组统计
F1 F2:A  张1
A  张1
A  王1
B  张3
C  李4
B  张3
结果
A 2
B 1
C 1

解决方案 »

  1.   

    group by f1,f2

    distinct
      

  2.   

    select F1,count(1) from (select distinct * from 表) t group by F1
      

  3.   

    --处理表重复值
    /******************************************************************************************************************************************************
    Num、Name相同的重复值记录,只保留一条整理人:中国风(Roy)日期:2008.06.06
    ******************************************************************************************************************************************************/--> --> (Roy)生成測試數據
     
    if not object_id('Tempdb..#T') is null
    drop table #T
    Go
    Create table #T([Num] int,[Name] nvarchar(1))
    Insert #T
    select 1,N'A' union all
    select 1,N'A' union all
    select 1,N'A' union all
    select 2,N'B' union all
    select 2,N'B'
    Go方法1:
    if object_id('Tempdb..#') is not null
    drop table #
    Select distinct * into # from #T--排除重复记录结果集生成临时表#truncate table #T--清空表insert #T select * from # --把临时表#插入到表#T中--查看结果
    select * from #T/*
    Num         Name
    ----------- ----
    1           A
    2           B(2 行受影响)
    */--重新执行测试数据后用方法2
    方法2:alter table #T add ID int identity--新增标识列
    go
    delete a from  #T a where  exists(select 1 from #T where Num=a.Num and Name=a.Name and ID>a.ID)--只保留一条记录
    go
    alter table #T drop column ID--删除标识列--查看结果
    select * from #T/*
    Num         Name
    ----------- ----
    1           A
    2           B(2 行受影响)*/--重新执行测试数据后用方法3
    方法3:
    declare Roy_Cursor cursor local for
    select count(1)-1,Num,Name from #T group by Num,Name having count(1)>1
    declare @con int,@Num int,@Name nvarchar(1)
    open Roy_Cursor
    fetch next from Roy_Cursor into @con,@Num,@Name
    while @@Fetch_status=0
    begin 
    set rowcount @con;
    delete #T where Num=@Num and Name=@Name
    set rowcount 0;
    fetch next from Roy_Cursor into @con,@Num,@Name
    end
    close Roy_Cursor
    deallocate Roy_Cursor--查看结果
    select * from #T
    /*
    Num         Name
    ----------- ----
    1           A
    2           B(2 行受影响)
    */
      

  4.   

    declare @tb table (f1 varchar(20),f2 varchar(20))
    insert into @tb select 'a','张1'
    insert into @tb select 'a','张1'
    insert into @tb select 'a','王1'
    insert into @tb select 'b','张3'
    insert into @tb select 'c','李4'
    insert into @tb select 'b','张3'
    select f1,count(distinct f2) as con
    from @tb
    group by f1f1 con
    a 2
    b 1
    c 1
      

  5.   

    --以上處理
    select F1,count(distinct f2) from t group by F1