2015-04-02 81 views
0

我想编写一个查询来复制从一个表中设置的行到另一个表以这种格式插入与列多行分为单列

Table 1 
ColumnName  ColumnValue RowId 

Column1    Value1   1 
Column2    Value2   1 
Column3    Value3   1 
Column1    Value4   2 
Column2    Value5   2 
Column3    Value6   2 
Column1    Value7   3 
Column2    Value8   3 
Column3    Value9   3 

Table2 
Column1   Column2  Column3 
Value1   Value2  Value3  
Value4   Value5  Value6 
Value7   Value8  Value9   

这里基本上表1是输入和表2是我正在尝试输出。我使用了数据透视表和行号,但都没有工作。

什么是插入查询来实现这一点。这里来自表1的rowId 1的所有行将形成table 2的一行。

+1

是否总是有一定数量的列? – Hogan 2015-04-02 22:19:38

+0

是的,只有3列。列名仅为唯一。我尝试在列上旋转,但无法使用它插入插入。 – James 2015-04-02 22:20:25

回答

1
select rowID, 
     max(case when columnName = 'Column1' then value else null end) as column1, 
     max(case when columnName = 'Column2' then value else null end) as column2, 
     max(case when columnName = 'Column3' then value else null end) as column3 
from table1 
group by rowID 
+0

谢谢,但我必须编写一个插入查询,以便在表2中转储数据。 – James 2015-04-02 22:24:28

+0

好的,为什么这个问题只是在代码之前插入表2(c1,c2,c3,c4)'以上。 – Hogan 2015-04-02 22:26:36

+0

在我的情况下,value列是文本列,max不允许在其上。此外,而不是越来越一行我得到3行用空了另外两列,列1 \t列2栏3 值1 NULL \t NULL NULL值2 \t NULL \t NULL NULL \t \t值3 – James 2015-04-02 22:33:18