如何在SQl中对齐合并数据

时间:2016-09-12 22:29:33

标签: sql sql-server-2008

我想将三个表组合到MSSQl2008的Final Table中。我的问题在于以最终表格式合并数据。另一个问题是每个表中的列数接近100列,因此我需要一个有效的代码来创建最终表

我需要一个会生成Final表的SQl脚本

<h1> Table 2008</h1>
<table border = 1>
 <tr>
   <td> ID </Td>
   <td> Sample_year </Td>
   <td> Total_at_t-5 </Td>
   <td> Total_at_t-4 </Td>
 </tr>
<tr>
   <td> MMM  </Td>
   <td> 2008  </Td>
   <td>  5.25 </Td>
   <td>  65.25</Td>
 </tr>
  </table>

<p> </p>

<h1> Table 2011</h1>
<table header = "2011"  border = 1>
 <tr>
   <td> ID </Td>
   <td> Sample_year </Td>
   <td> Total_at_t-6 </Td>
   <td> Total_at_t-5 </Td>
 </tr>
<tr>
   <td> MMM  </Td>
   <td> 2011  </Td>
   <td>  7.25 </Td>
   <td>  98.25</Td>
 </tr>
  </table>

<p> </p>

<h1> Table 2013</h1>
<table header = "2013" border = 1>
 <tr>
   <td> ID </Td>
   <td> Sample_year </Td>
   <td> Total_at_t-7 </Td>
   <td> Total_at_t-6 </Td>
 </tr>
<tr>
   <td> MMM  </Td>
   <td> 2013  </Td>
   <td> 3.25  </Td>
   <td> 7.25</Td>
 </tr>
  </table>

<p> </p>
<h1> Table Final</h1>
<table hearder = "Final Table"  border = 1>
 <tr>
   <td> ID </Td>
   <td> Sample_year </Td>
   <td> Total_at_t-7 </Td>
   <td> Total_at_t-6 </Td>
   <td> Total_at_t-5 </Td>
   <td> Total_at_t-4 </Td>
 </tr>
<tr>
   <td> MMM </Td>
   <td> NULL </Td>
   <td> NULL </Td>
   <td> NULL </Td>
   <td> 5.25 </Td>
   <td> 65025 </Td>
 </tr>
<tr>
   <td> MMM </Td>
   <td> 2011 </Td>
   <td> NULL </Td>
   <td> 7.25</Td>
   <td> 98.25 </Td>
   <td> NULL </Td>
 </tr>
<tr>
   <td> MMM </Td>
   <td> 2013 </Td>
   <td> 3.25 </Td>
   <td> 7.25 </Td>
   <td> NUll </Td>
   <td> NUll</Td>
 </tr>
  </table>

1 个答案:

答案 0 :(得分:0)

假设SQL数据库中存在Table,如果是这种情况,您只需要使用Unionhttp://www.w3schools.com/sql/sql_union.asp)将它们连接在一起

declare @T2008 table (id varchar(3), sample_year int, [total_at_t-5] decimal(10, 2), [total_at_t-4] decimal(10, 2))

insert into @T2008 values ('MMM', 2008, 5.25, 65.25)

declare @T2011 table (id varchar(3), sample_year int, [total_at_t-6] decimal(10, 2), [total_at_t-5] decimal(10, 2))

insert into @T2011 values ('MMM', 2011, 7.25, 98.25)

declare @T2013 table (id varchar(3), sample_year int, [total_at_t-7] decimal(10, 2), [total_at_t-6] decimal(10, 2))

insert into @T2013 values ('MMM', 2013, 3.25, 7.25)

select id, sample_year, null as [total_at_t-7], null as [total_at_t-6], [total_at_t-5], [total_at_t-4]
from @T2008

union

select id, sample_year, null, [total_at_t-6], [total_at_t-5], null
from @T2011

union

select id, sample_year, [total_at_t-7], [total_at_t-6], null, null
from @T2013