一个test表
有3个字段,
id   aa   bb
1    a    1
2    a    2
3    a    2
4    a    3
5    b    1
6    b    2
我想查询当aa列等于a时,bb列一共有多少条不同记录。
就是结果查出个3
Sql语句怎么写??

解决方案 »

  1.   

    select aa,count(distinct bb) as 記錄
    from test
    group by aa
      

  2.   

    use Tempdb
    go
    --> --> 
     
    if not object_id(N'Tempdb..#T') is null
    drop table #T
    Go
    Create table #T([id] int,[aa] nvarchar(1),[bb] int)
    Insert #T
    select 1,N'a',1 union all
    select 2,N'a',2 union all
    select 3,N'a',2 union all
    select 4,N'a',3 union all
    select 5,N'b',1 union all
    select 6,N'b',2
    Go
    Select [aa],COUNT(DISTINCT [bb]) AS con from #T GROUP BY [aa]
    /*
    aa con
    a 3
    b 2
    */
      

  3.   

    select aa,count(distinct bb) as 数 from test group by aa
      

  4.   

    select aa,count(distinct bb)   from test group by aa
      

  5.   

    select aa,count(distinct bb) from test where aa='a'楼上几位大侠,你们干嘛都用group 
    我这样可以不丫?
      

  6.   

    不可以 有聚合函数 必须要GROUP BY 分组
      

  7.   

    SELECT DISTINCT
            [aa] ,
            COUNT([bb]) OVER ( PARTITION BY [aa] )
    FROM    ( SELECT DISTINCT
                        [aa] ,
                        [bb]
              FROM      #T
            ) AS d
      

  8.   

    select count(bbc) from (select count(bb) bbc from test where aa='a' group by bb) c;
      谢谢大家了!