2017-09-26 83 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實現了橫向連接,它比僅僅不透明數據更強大。