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

多表查询的问题
现在有我多个表
表的结构
id(int)       bt(varchar)     cs(int)
有10多个表,表的结构都一样
现在ID是自动标示
cs是写入不同的数
我现在想查询这10多个表cs字段共和,条件是bt=XX
要怎   么实现啊




------解决方案--------------------
select sum(cs) cs的和 from
(
select * from tb1
union all
select * from tb2
...
union all
select * from tb10
) t
where bt = 'xx '
------解决方案--------------------
create table #T(id int,bt varchar(50),cs int)
insert into #T
select id,bt,cs from table1 union all
select id,bt,cs from table2 union all
……………………………………………………
select id,bt,cs from tableN

select sum(cs) from #T where bt=XX group by bt
------解决方案--------------------
select bt,sum(cs) from
(
select * from tb1
union all
select * from tb2
...
union all
select * from tb10
) t
where bt = 'xx '
group by bt
------解决方案--------------------
id(int) bt(varchar) cs(int)
有10多个表,表的结构都一样
现在ID是自动标示
cs是写入不同的数
我现在想查询这10多个表cs字段共和,条件是bt=XX
--------------------------------------------
select (sum(a.cs)+sum(b.cs)+sum(c.cs)+.......+sum(j.cs)) as totalCount
from tab1 a full join tab2 b on a.id=b.id..........full join tab10 j on a.id=j.id
where a.bt=XX and b.bt=xx and ......j.bt=xx