create table Table1(ctn varchar(10) , ship varchar(10))
insert into table1 values('123', 'APL') 
insert into table1 values('187', 'APL') 
insert into table1 values('143', 'APL') 
insert into table1 values('456', 'CMA')
insert into table1 values('111', 'CMA')
insert into table1 values('45678', 'NS')
insert into table1 values('789', 'OOCL')
insert into table1 values('99999', 'OOCL')
create table Table2(ctn varchar(10))
insert into table2 values('123')
insert into table2 values('187') 
insert into table2 values('456')
insert into table2 values('111')
insert into table2 values('45678')
insert into table2 values('789')
insert into table2 values('11551')
insert into table2 values('4555')
insert into table2 values('78889')
go 我想在table1里面找进场的总数和公司名,在table2里面出现了就说已进来,没出现就是没进来
然后生成下表
ship   总数 已进来  未进来
APL     3     2        1
CMA     2     2        0
NS      1     1        0
OOCL    2     1        1应该怎么写呢~!

解决方案 »

  1.   


    select a.ship ,count(1) as 总数,
    count(case when b.ctn is not null then 1 end) as 已进来,
    count(case when b.ctn is null then 1 end) as 未进来
    from table1 a left join table2 b
    on a.ctn=b.ctn
    group by a.shipship       总数          已进来         未进来
    ---------- ----------- ----------- -----------
    APL        3           2           1
    CMA        2           2           0
    NS         1           1           0
    OOCL       2           1           1
    警告: 聚合或其他 SET 操作消除了空值。(4 行受影响)
      

  2.   


    select ship,
    总数=count(1),
    已进来=count(b.ctn),
    未进来=sum(case when b.ctn is null then 1 else 0 end)
    from table1 a 
    left join table2 b on a.ctn=b.ctn
    group by ship
      

  3.   

    select ship,
    总数=count(1),
    已进来=count(b.ctn),
    未进来=count(1)-count(b.ctn)
    from table1 a 
    left join table2 b on a.ctn=b.ctn
    group by ship
      

  4.   

    select ship,
    总数  =count(a.ctn),
    已进来=count(b.ctn),
    未进来=count(a.ctn)-count(b.ctn)
    from table1 a 
    left join table2 b on a.ctn=b.ctn
    group by ship