船表:(船号,船厂,船种)
HullNo  Yard      Type
H2317  现代重工   Bulk
H2319   三星      Container期望统计格式:
船厂      船种       艘数
现代重工  Bulk        1
现代重工  Container   0
三星      Bulk        0
三星      Container   1有很多船厂,拒绝穷举case,谢谢

解决方案 »

  1.   

    Select Yard ,Type,Count(*) From tablename Group By Yard ,Type
      

  2.   

    select Yard,Type,艘数=count(1) from 表 group by Yard,Type
      

  3.   

    select 船厂,船种,count(*) 艘数 from 表 group by 船厂,船种
      

  4.   

    select 船厂=a.Yard,船种=b.Type,艘数=isnull(c.CT,0) from
    (select Yard from 表 group by Yard) a
    cross join
    (select Type from 表 group by Type) b
    left join
    (select Yard,Type,CT=count(1) from 表 group by Yard,Type) c
    on a.Yard=c.Yard and b.Type=c.Type
      

  5.   

    --原始数据:@T
    declare @T table(HullNo varchar(5),Yard varchar(8),Type varchar(9))
    insert @T
    select 'H2317','现代重工','Bulk' union all
    select 'H2319','三星','Container'select 船厂=a.Yard,船种=b.Type,艘数=isnull(c.CT,0) from
    (select Yard from @T group by Yard) a
    cross join
    (select Type from @T group by Type) b
    left join
    (select Yard,Type,CT=count(1) from @T group by Yard,Type) c
    on a.Yard=c.Yard and b.Type=c.Type
    order by a.Yard desc
    /*
    船厂 船种 艘数
    现代重工 Bulk 1
    现代重工 Container 0
    三星 Bulk 0
    三星 Container 1
    */
      

  6.   

    create table tb(HullNo varchar(10),Yard varchar(10),Type varchar(10))
    insert into tb values('H2317' , '现代重工',   'Bulk')
    insert into tb values('H2319' , '三星'    ,  'Container')
    goselect t.Yard 船厂 , t.type 船种 , sum(case when tb.hullno is null then 0 else 1 end) 艘数 from 
    (
      select t1.Yard , t2.type from
      (select Yard from tb) t1
      cross join
      (select Type from tb) t2
    ) t
    left join tb
    on t.yard = tb.yard and t.type = tb.type
    group by t.yard,t.type
    order by t.yard,t.type
    drop table tb/*
    船厂         船种       艘数          
    ---------- ---------- ----------- 
    三星         Bulk       0
    三星         Container  1
    现代重工     Bulk       1
    现代重工     Container  0
    (所影响的行数为 4 行)
    */