2017-09-26 114 views
0

我的表看起来像 - enter image description here拆分成SQL多行

我想实现这样的 - enter image description here

请帮助SQL

+0

列名是静态的还是动态的? –

+0

在Oracle中,您可以使用UNPIVOT,但我不知道它是否在SQL Server中可用。 –

回答

0

替换表名,并尝试

insert into yourTableName (CollegeID, DeptID, EmpID, Yr, Mnth, Act, Pred) values (234, 34, 4, 2017, 1, 6131.86, 6131.82) 
1

如果列名是静态的,你可能会使用UNION SELECT查询,如下所示:

Select CollegeID, DeptID, EmpID, "2017" As Y, "1" As Mnth, [Act201701] As Act, [Pred201701] As Pred from [SomeTable] 
UNION 
Select CollegeID, DeptID, EmpID, "2017" As Y, "2" As Mnth, [Act201702] As Act, [Pred201702] As Pred from [SomeTable] 
UNION 
Select CollegeID, DeptID, EmpID, "2017" As Y, "3" As Mnth, [Act201703] As Act, [Pred201703] As Pred from [SomeTable] 

其中SomeTable是您的表名称。

2

使用apply

select t.collegeid, t.deptid, t.empid, v.yr, v.mnth, v.act, v.pred 
from t outer apply 
    (values (act201701, pred201701, 2017, 1), 
      (act201702, pred201702, 2017, 2), 
      (act201703, pred201703, 2017, 3), 
    ) v(act, pred, yr, mnth); 

您还可以使用unpivot同样的事情。但是,apply实现了横向连接,它比仅仅不透明数据更强大。