sql 查询一对多,统计重复字段的问题!!求解
SQL
有
A表:AId AType CId B表: BId AId C表:CId CName
1 101 1 1 1 1 A
2 101 2 2 1 2 B
3 102 3 3 2 3 C
4 102 1 4 3
5 3
6 4
7 4
A与C是一对一关系,A与B是一对多关系。
需要根据CName分组统计A的总数,AType=101的总数,AType=102的总数以及B的总数
希望查询的结果是:
CName ACount AType(101) AType(102) BCount
A 2 1 1 4
B 1 1 0 1
C 1 0 1 2
现在的问题是当B表对应A表有多条数据时,会导致ACount统计重复数据,求大神回复!!!
--> 测试数据:@A表
declare @A表 table([AId] int,[AType] int,[CId] int)
insert @A表
select 1,101,1 union all
select 2,101,2 union all
select 3,102,3 union all
select 4,102,1
--> 测试数据:@B表
declare @B表 table([BId] int,[AId] int)
insert @B表
select 1,1 union all
select 2,1 union all
select 3,2 union all
select 4,3 union all
select 5,3 union all
select 6,4 union all
select 7,4
--> 测试数据:@C表
declare @C表 table([CId] int,[CName] varchar(1))
insert @C表
select 1,'A' union all
select 2,'B' union all
select 3,'C'
SELECT [CName] ,
( SELECT COUNT(1)
FROM @A表
WHERE [CId] = c.cid
) AS ACount ,
( SELECT COUNT(1)
FROM @A表
WHERE [CId] = c.cid
AND [AType] = 101
) AS [AType(101)] ,
( SELECT COUNT(1)
FROM @A表
WHERE [CId] = c.cid
AND [AType] = 102
) AS [AType(102)] ,
( SELECT COUNT(1)
FROM ( SELECT aa.CId
FROM @B表 bb
LEFT JOIN @A表 aa ON bb.AId = aa.AId
) b
WHERE cid = c.cid
) AS BCount
FROM @C表 c
/*
CName ACount AType(101) AType(102) BCount
----- ----------- ----------- ----------- -----------
A 2 1 1 4
B 1 1 0 1
C 1 0 1 2
(3 row(s) affected)
*/