有一表 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 allselect 2,'bbbbbb' union allselect 3,'cccccc' union allselect 4,'dddddd' union allselect 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 allselect 2,1,'aaaaaaa' union allselect 3,1,'aaaaaaa' union allselect 4,2,'aaaaaaa' union allselect 5,2,'aaaaaaa' union allselect 6,3,'aaaaaaa' union allselect 7,3,'aaaaaaa'select a.aid, ISNULL(COUNT(b.aid),0) as baid from A1 a left join B2 b on a.aid=b.aidgroup by a.aid/*aid baid---------------1 32 23 24 05 0*/
------解决方案--------------------
- SQL code
SELECT a.aid,baid=(SELECT COUNT(*) FROM B2 b WHERE a.aid=b.aid) FROM A1 a