两张表
STUID STUNAME
S1    张三
S2    李四
S3    赵五
STUID CLASSID
S1    1
S1    2
S1    3
S1    4
S3    1
S3    4查询结果
STU   STUNAME CLASSCOUNT
S1    张三     4
S2    李四     0
S3    赵五     2

解决方案 »

  1.   


    select a.STUID,a.STUNAME,CLASSCOUNT=count(b.CLASSID)
    from 表1 a inner join 表2 b on a.STUID=b.STUID
    group by a.STUID,a.STUNAME
      

  2.   

    create table tb1(STUID varchar(2),STUNAME varchar(10))
    insert tb1
    select 'S1','张三'
    union select 'S2','李四'
    union select 'S3','赵五'
    create table tb2(STUID varchar(2),CLASSID int)
    insert tb2
    select 'S1',1
    union select 'S1',2
    union select 'S1',3
    union select 'S1',4
    union select 'S3',1
    union select 'S3',4
    select a.STUID,a.STUNAME,CLASSCOUNT=count(b.CLASSID)
    from tb1 a left join tb2 b on a.STUID=b.STUID
    group by a.STUID,a.STUNAMEdrop table tb1,tb2
    /*
    STUID STUNAME    CLASSCOUNT  
    ----- ---------- ----------- 
    S2    李四         0
    S1    张三         4
    S3    赵五         2(3 row(s) affected)*/
      

  3.   

    create table tab1(STUID varchar(2),STUNAME varchar(6))
    insert tab1
    select 'S1','张三' union all
    select 'S2','李四' union all
    select 'S3','赵五'create table tab2(STUID varchar(2),CLASSID int)
    insert tab2
    select 'S1',1 union all
    select 'S1',2 union all
    select 'S1',3 union all
    select 'S1',4 union all
    select 'S3',1 union all
    select 'S3',4--查询结果
    --STU   STUNAME CLASSCOUNT
    --S1    张三     4
    --S2    李四     0
    --S3    赵五     2
    select tab1.STUID,tab1.STUNAME,count(tab2.CLASSID) 
    from tab1 left join tab2 on tab1.STUID=tab2.STUID
    group by tab1.STUID,tab1.STUNAMEdrop table tab1,tab2
      

  4.   

    (6 行受影响)
    STUID STUNAME 
    ----- ------- -----------
    S2    李四      0
    S1    张三      4
    S3    赵五      2