phone    flag
1         a
1         b
1         b
2         b
3         c
3         c
4         d
我想查询每个flag有几个phone和每个flag有几个?
查询出来的效果:
flag    flagnum     phonenum
a         1           1
b         3           2
c         2           1
d         1           1

解决方案 »

  1.   

    create table test(phone int,flag nchar(2))
    insert test
    select 1         ,'a' union all
    select 1         ,'b' union all
    select 1         ,'b' union all
    select 2         ,'b' union all
    select 3         ,'c' union all
    select 3         ,'c' union all
    select 4         ,'d'
    select * from testselect 
      flag,
      count(flag),
      count(distinct phone)
    from test 
    group by flagdrop table test
      

  2.   

    select flag,count(flag) as flagnum,count(distinct phone) as phonenum
    from tb
    group by flag