在具有相同列名

时间:2016-09-23 16:43:34

标签: sql sql-server

我有10个名为T1,T2,T3,...,T10的表,每个存储列名为ID,C1,C2,C3 ....,C100。

我想创建一个汇总表,它存储相应列的总和,即T1.C1 + T2.C1 + T3.C1,T1.C2 + T2.C2 + T3.C2等等。

如果只有几列,我可以做一些事情:

select T1.C1 + T2.C1 + T3.C1 as C1, T1.C2 + T2.C2 + T3.C2 as C2
from T1
inner join T2
on T1.ID = T2.ID
inner join T3
on T1.ID = T3.ID

但我要添加100列,而且我有大量的表。

3 个答案:

答案 0 :(得分:2)

假设ID是每个表中的主键:

select ID, sum(c1) as c1, sum(c2) as c2 --,...
from(
   select ID, c1, c2 --,..
   from T1
   union all
   select ID, c1, c2 --,..
   from T2
   -- union all ..
) T
group by ID

答案 1 :(得分:1)

如果你不介意动态

Declare @Cols varchar(max) = '>>>'
;with cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
      cte2(N) As (Select Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a, cte1 b) A )   --<< 100 Columns
Select @Cols = Replace(@Cols+',C'+cast(N as varchar(5))+'=sum(C'+cast(N as varchar(5))+')','>>>,','') from cte2

Declare @From varchar(max) = '>>>'
;with cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
      cte2(N) As (Select Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a) A )   --<< 10 Tables
Select @From = Replace( @From+'Union All Select * from T'+cast(N as varchar(5))+' ','>>>Union All','') from cte2

Declare @SQL varchar(max) ='Select ID,'+@Cols+' From ('+@From+') A Group By ID'  
Exec(@SQL)

答案 2 :(得分:1)

为了好玩,您可能需要考虑以下事项。子查询将在EAV(元素属性值)结构中规范化您的数据

Declare @XML xml = (Select * From ( Select * from T1 Union All Select * from T2 Union All Select * from T3 Union All Select * from T4 Union All Select * from T5 Union All Select * from T6 Union All Select * from T7 Union All Select * from T8 Union All Select * from T9 Union All Select * from T10) A for XML RAW)
Select ID
      ,Item
      ,Value = Sum(Value)
 From (
        Select ID    = r.value('@ID','int')                            -- << Key ID (Case Sensitive)    
              ,Item  = attr.value('local-name(.)','varchar(50)')
              ,Value = attr.value('.','money')                         -- << Set Appropriate Data Type
         From  @XML.nodes('/row') as A(r)                         
         Cross Apply A.r.nodes('./@*[local-name(.)!="id"]') as B(attr) -- << Key ID (Case Sensitive)    
      ) A
 Group By ID,Item