首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

关于多表统计数量的SQL语句,该怎么解决

2012-05-15 
关于多表统计数量的SQL语句A表:AIDAName1a2b3c4d5EB表BIDAID112131415262728393104想通过SQL语句查询出如

关于多表统计数量的SQL语句
A表:
AID AName
1 a
2 b
3 c
4 d
5 E
B表
BID AID
1 1
2 1
3 1
4 1
5 2
6 2
7 2
8 3
9 3
10 4

想通过SQL语句查询出如下表样式的结果:
AID AName count
1 a4
2 b3
3 c2
4 d1
5 e0

count是统计B表中有AID的数量的,这样的SQL语句怎么写?!求指导!!!!!!!!!!!!!!!!!!!

[解决办法]
select A.AID,A.AName,count(*) as count from A inner join B on A.AID=B.AID group by A.AID,A.AName
[解决办法]
内连接与外连接的问题啊
[解决办法]

SQL code
select A.AID,A.AName,case isnull(max(B.AID),0) when 0 then 0 else COUNT(*) end as count  from A left join B on A.AID=B.AID group by A.AID,A.AName
[解决办法]
SQL code
select a.aid,a.aname,count(b.aid) c from #tempA a left join #tempB b on a.aid=b.aid group by a.aid,a.aname/*aid aname c1    a      42    b      23    c      24    d      15    e      0*/
[解决办法]
第一种情况:不显示A表中无关记录
SQL code
use DBTestgoif  OBJECT_ID('A') is not null drop table Agoif OBJECT_ID('B') is not null drop table Bgocreate table A(AID int,AName nvarchar(20))create table B(BID int,AID int,step int)insert into Aselect 1,'A' union allselect 2,'B'insert into Bselect 1,1,1 union allselect 2,1,2--第一个select A.AID,A.AName,COUNT(*) as count from A inner join Bon A.AID=B.AID group by A.AID,A.AName--第二个select A.AID,A.AName,sum(case B.step when 1 then 1 else 0 end ) as count1,sum(case B.step when 2 then 1 else 0 end ) as count2 from A inner join Bon A.AID=B.AID group by A.AID,A.AName 

热点排行