表A:
daLei         xiaoLei
湖北            武汉
湖北            黄石
湖北            孝感
长沙            湖南
长沙            岳阳我想根据上表获得的信息如下:
Province        City            CityAmount
湖北            武汉                3
湖北            黄石                3
湖北            孝感                3
长沙            湖南                2
长沙            岳阳                2就是查询每个省下面市的数量
并且还要按照上面的格式

解决方案 »

  1.   

    SELECT 
    daLei    ,    
    xiaoLei ,
    (SELECT COUNT(1) FROM TB WHERE daLeI=T.daLei)
    FROM TB T
      

  2.   

    select *,(select count(*) from tb where province=t.province)   as CityAmount
    from tb
      

  3.   


    select A.*,B.CityAmount   from A,
    (select dalei,count(1) as CityAmount  from A group by dalei )B
    where a.dalei=b.dalei
      

  4.   

    --> 测试数据:@tb
    declare @tb table([daLei] varchar(4),[xiaoLei] varchar(4))
    insert @tb
    select '湖北','武汉' union all
    select '湖北','黄石' union all
    select '湖北','孝感' union all
    select '长沙','湖南' union all
    select '长沙','岳阳'select *,(select count(1) from @tb where [daLei]=a.[daLei]) as 统计
     from @tb a
    /*
    daLei xiaoLei 统计
    ----- ------- -----------
    湖北    武汉      3
    湖北    黄石      3
    湖北    孝感      3
    长沙    湖南      2
    长沙    岳阳      2(5 行受影响)
    */
      

  5.   

    select
      a.daLei as Province,
      a.xiaolei as city,
      b.num
    from
      tb a
    left join
      (select daLei,count(1) as num from tb group by dalei)b 
    on
       a.daLei=b.daLei
      
      

  6.   

    --sql 2005
    create table #tb ([daLei] varchar(4),[xiaoLei] varchar(4))
    insert #tb
    select '湖北','武汉' union all
    select '湖北','黄石' union all
    select '湖北','孝感' union all
    select '长沙','湖南' union all
    select '长沙','岳阳'select dalei,xiaolei,count(dalei) over(partition by dalei ) as CityAmount
    from #tb
    order by count(dalei) over(partition by dalei ) desc