两张数据表联合查询的问题

homking 2012-03-07 03:23:42
假设有表A
a_id    a_name
1    test1
2    test2
3    test3


表B
b_id    a_id
1    1
2    2
3    3
4    1
5    2
6    1

现在想要查询结果是列出表A中所有项目在表B中出现的次条数
显示如下
a_id    a_name    a_count
1    test1    3
2    test2    2
3    test3    1
...全文
80 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
nightgoblin 2012-03-07
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 homking 的回复:]
假设有表A
a_id a_name
1 test1
2 test2
3 test3


表B
b_id a_id
1 1
2 2
3 3
4 1
5 2
6 1

现在想要查询结果是列出表A中所有项目在表B中出现的次条数
显示如下
a_id a_name a_count
1 test1 3
2 test2 2
3 test3 1
[/Quote]

USE tempdb;
GO
IF OBJECT_ID('a') IS NOT NULL
DROP TABLE a;
IF OBJECT_ID('b') IS NOT NULL
DROP TABLE b;
GO
CREATE TABLE a
(a_id INT,
a_name VARCHAR(10));
GO
CREATE TABLE b
(b_id INT,
a_id INT);
GO
INSERT INTO a VALUES (1,'test1');
INSERT INTO a VALUES (2,'test2');
INSERT INTO a VALUES (3,'test3');
INSERT INTO a VALUES (4,'test4');
INSERT INTO a VALUES (5,'test5');
INSERT INTO a VALUES (6,'test6');
INSERT INTO b VALUES (1,1);
INSERT INTO b VALUES (2,1);
INSERT INTO b VALUES (3,1);
INSERT INTO b VALUES (4,2);
INSERT INTO b VALUES (5,2);
INSERT INTO b VALUES (6,3);
GO
SELECT a.a_id,a.a_name,COUNT(b.a_id) AS acount FROM b INNER JOIN a ON b.a_id=a.a_id GROUP BY a.a_id,a.a_name;
--查询结果
a_id a_name acount
1 test1 3
2 test2 2
3 test3 1
勿勿 2012-03-07
  • 打赏
  • 举报
回复
眼睛花了。
  • 打赏
  • 举报
回复
select a.*,c.* from a
inner join
(select b.*,count(a_id) as a_count from b group by a_id    a_name    )c
on a.aid=c.aid
叶子 2012-03-07
  • 打赏
  • 举报
回复

select a.a_id ,a.a_name,count(1) as a_count
from 表A a left join 表B b
on a.a_id=b.a_id group by a.a_id ,a.a_name
叶子 2012-03-07
  • 打赏
  • 举报
回复

--> 测试数据: @表A
declare @表A table (a_id int,a_name varchar(5))
insert into @表A
select 1,'test1' union all
select 2,'test2' union all
select 3,'test3'

--> 测试数据: @表B
declare @表B table (b_id int,a_id int)
insert into @表B
select 1,1 union all
select 2,2 union all
select 3,3 union all
select 4,1 union all
select 5,2 union all
select 6,1

select a.a_id ,a.a_name,count(1) as cnt from @表A a left join @表B b
on a.a_id=b.a_id group by a.a_id ,a.a_name
/*
a_id a_name cnt
----------- ------ -----------
1 test1 3
2 test2 2
3 test3 1
*/
homking 2012-03-07
  • 打赏
  • 举报
回复
假设有表A
a_id a_name
1 test1
2 test2
3 test3


表B
b_id a_id
1 1
2 2
3 3
4 1
5 2
6 1

现在想要查询结果是列出表A中所有项目在表B中出现的次条数
显示如下
a_id a_name a_count
1 test1 3
2 test2 2
3 test3 1
David8977 2012-03-07
  • 打赏
  • 举报
回复
select a_id,count(a_id) as a_count from a group by a_id
  • 打赏
  • 举报
回复
看着好晕

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧