表1
aid   f1    f2
1     XX1   XX1
2     XX2   XX2
3     XX3   XX3表2
fid   t1    aid
1     图片  1
2     图片  1
3     视频  1
4     视频  1
5     图片  2
============
要求得出下面结果
aid   f1    f2   m1(视频总数)  m2(图片总数)
1     XX1   XX1  2             2
2     XX2   XX2  0             1
3     XX3   XX3  0             0

解决方案 »

  1.   

    select a.fid,a.f1,a.f2,(select count(*) from 表2 b where b.aid=a.aid) as 视频总数,(select count(*) from 表2 c where c.aid=a.aid) as 图片总数 from 表1 a
      

  2.   

    create table T1(aid int, f1 varchar(10), f2 varchar(10))
    insert T1 select 1,     'XX1',   'XX1'
    union all select 2,     'XX2',   'XX2'
    union all select 3,     'XX3',   'XX3'create table T2(fid int, t1 varchar(10), aid int)
    insert T2 select 1,     '图片',  1
    union all select 2,     '图片',  1
    union all select 3,     '视频',  1
    union all select 4,     '视频',  1
    union all select 5,     '图片',  2select T1.*, m1=isnull(T2.m1, 0), m2=isnull(T2.m2, 0) from T1
    left join
    (
    select aid,
    m1=sum(case when t1='视频' then 1 else 0 end),
    m2=sum(case when t1='图片' then 1 else 0 end)
    from T2
    group by aid
    )T2 on T1.aid=T2.aid
      

  3.   

    --result
    aid         f1         f2         m1          m2          
    ----------- ---------- ---------- ----------- ----------- 
    1           XX1        XX1        2           2
    2           XX2        XX2        0           1
    3           XX3        XX3        0           0(3 row(s) affected)
      

  4.   

    create table T2(fid int, t1 varchar(10), aid int)
    insert T2 select 1,     '图片',  1
    union all select 2,     '图片',  1
    union all select 3,     '视频',  1
    union all select 4,     '视频',  1
    union all select 5,     '图片',  2select *,
    视频总数=(select count(*) from T2 where aid=tmp.aid and t1='视频'),
    图片总数=(select count(*) from T2 where aid=tmp.aid and t1='图片')
    from T1 as tmp--result
    aid         f1         f2         视频总数        图片总数        
    ----------- ---------- ---------- ----------- ----------- 
    1           XX1        XX1        2           2
    2           XX2        XX2        0           1
    3           XX3        XX3        0           0(3 row(s) affected)
      

  5.   

    --sorry, 楼上的少了一个T1create table T1(aid int, f1 varchar(10), f2 varchar(10))
    insert T1 select 1,     'XX1',   'XX1'
    union all select 2,     'XX2',   'XX2'
    union all select 3,     'XX3',   'XX3'