日期:2014-05-18  浏览次数:20643 次

SQL多表统计总数?请大家帮帮忙?
清问
比如我有3个表一模一样的表,要统计某列字段出现一共出现次数,怎么写呀。

A表

a b
1 1
2 2
3 3
4 4
5 5

B表
a b
11 1
22 2
33 3
4 4
55 5

C表
a b
11 1
2 2
3 3
44 4
55 5

统计a列
结果为
a sum
1 1
2 2
3 2
4 2
5 1
11 2
22 1
33 1
44 1
55 2

请大家帮帮忙?

------解决方案--------------------
SQL code
create table A(a int, b int)
insert into a values(1 ,1)
insert into a values(2 ,2)
insert into a values(3 ,3)
insert into a values(4 ,4)
insert into a values(5 ,5)
create table b(a int, b int)
insert into b values(11 ,1)
insert into b values(22 ,2)
insert into b values(33 ,3)
insert into b values(4 ,4)
insert into b values(55 ,5)
create table C(a int, b int)
insert into c values(11 ,1)
insert into c values(2 ,2)
insert into c values(3 ,3)
insert into c values(44, 4)
insert into c values(55, 5)
go

select a , count(1) [sum] from 
(
select a , b from a
union all
select a , b from b
union all
select a , b from c
) t
group by a
 
/*
a           sum         
----------- ----------- 
1           1
2           2
3           2
4           2
5           1
11          2
22          1
33          1
44          1
55          2

(所影响的行数为 10 行)
*/

drop table a,b , c