日期:2014-05-18  浏览次数:20480 次

查询合计不知道怎么查哦!!求大神!!
有一表 A
----aid--------acontent---------------------------
  1 aaaaaa
  2 bbbbbb
  3 cccccc
  4 dddddd
  5 eeeeee
 另一表 B
----bid---------aid-------------bcontent---------
  1 1 aaaaaaa
  2 1 aaaaaaa
  3 1 aaaaaaa
  4 2 aaaaaaa
  5 2 aaaaaaa
  6 3 aaaaaaa
  7 3 aaaaaaa

想得到结果
-----aid---------bCount------------------------
  1 3
  2 2
  3 3
  4 0
  5 0


假如A表是消息表,b表是回复表
我想求出每条消息共有几条回复
求高手写出sql语句啊


------解决方案--------------------
SQL code

--> 测试数据:[A1]
if object_id('[A1]') is not null drop table [A1]
create table [A1]([aid] int,[acontent] varchar(6))
insert [A1]
select 1,'aaaaaa' union all
select 2,'bbbbbb' union all
select 3,'cccccc' union all
select 4,'dddddd' union all
select 5,'eeeeee'
--> 测试数据:[B2]
if object_id('[B2]') is not null drop table [B2]
create table [B2]([bid] int,[aid] int,[bcontent] varchar(7))
insert [B2]
select 1,1,'aaaaaaa' union all
select 2,1,'aaaaaaa' union all
select 3,1,'aaaaaaa' union all
select 4,2,'aaaaaaa' union all
select 5,2,'aaaaaaa' union all
select 6,3,'aaaaaaa' union all
select 7,3,'aaaaaaa'

select 
    a.aid,
    ISNULL(COUNT(b.aid),0) as baid 
from 
    A1 a 
left join 
    B2 b 
on 
    a.aid=b.aid
group by 
    a.aid
/*
aid    baid
---------------
1    3
2    2
3    2
4    0
5    0
*/

------解决方案--------------------
SQL code

SELECT a.aid,baid=(SELECT COUNT(*) FROM B2 b WHERE a.aid=b.aid) FROM A1 a