有如下两个表: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
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
解决方案 »
- sql2008无日志文件附加数据库失败,无法打开数据库 'xxx' 版本 611。请将该数据库升级为最新
- 求查询语句-最后日期的列表
- 大虾帮忙!取数据问题.
- 求一sql语句
- SQL 服务器: 消息 823,级别 24,状态 2,行 1
- SQL2000-SERVER中为什么varchar字段我写进去中文就是 "??" 和"???"而数字,字母可以正常显示?
- 交易式复写主键被拿掉的困惑
- 很难的问题:text file to sqlserver
- 着急,很着急……导出数据库出现错误……
- 提示服务器太忙,无法满足请求,连接过多
- 使用 bcp的问题
- 通过链接服务器向DB2中写数据,有默认值的字段反要指定?
GROUP BY a.Id,A.[Text]
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 行受影响)
where a.id=b.id
group by a.id,a.text