有如下两个表:A,B。A:
ID  Text
--------
0   q
1   w
2   e
3   rB:
ID  AID Text
----------------
0   0   qwe
1   0   efrfdf
2   0   rewf
3   1   greff
4   1   tre
5   2   rfdffd
6   2   redd
7   2   re4dfd
8   2   4arf
9   3   gre
10  3   er5fdf
11  3   43e
12  3   rewfd其中 A.ID 与 B.AID 为 1 对 n 的关系。我想要把 A 表内容全部输出,而且新增一列,为 A 表每一个记录在 B 表中的个数。如下表:R:
ID  Text    BCount
--------------------
0   q       3
1   w       2
2   e       4
3   r       4

解决方案 »

  1.   

    SELECT a.id,a.[Text],count(Aid) BCount FROM a LEFT JOIN B ON A.id=b.Aid
    GROUP BY a.Id,A.[Text]
      

  2.   

    --> 测试数据: [A]
    if object_id('[A]') is not null drop table [A]
    go
    create table [A] (ID int,Text varchar(1))
    insert into [A]
    select 0,'q' union all
    select 1,'w' union all
    select 2,'e' union all
    select 3,'r'
    --> 测试数据: [B]
    if object_id('[B]') is not null drop table [B]
    go
    create table [B] (ID int,AID int,Text varchar(6))
    insert into [B]
    select 0,0,'qwe' union all
    select 1,0,'efrfdf' union all
    select 2,0,'rewf' union all
    select 3,1,'greff' union all
    select 4,1,'tre' union all
    select 5,2,'rfdffd' union all
    select 6,2,'redd' union all
    select 7,2,'re4dfd' union all
    select 8,2,'4arf' union all
    select 9,3,'gre' union all
    select 10,3,'er5fdf' union all
    select 11,3,'43e' union all
    select 12,3,'rewfd'select A.*,BCount=(select count(*) from B where b.AID=a.ID) from [A]ID          Text BCount
    ----------- ---- -----------
    0           q    3
    1           w    2
    2           e    4
    3           r    4(4 行受影响)
     
      

  3.   

    select a.*,count(1) from a,b
    where a.id=b.id
    group by a.id,a.text