在sql中拆分为多行
我的桌子看起来像- 我想做到这一点-在sql中拆分为多行,sql,sql-server,Sql,Sql Server,我的桌子看起来像- 我想做到这一点- 请帮助SQL替换表名并重试 insert into yourTableName (CollegeID, DeptID, EmpID, Yr, Mnth, Act, Pred) values (234, 34, 4, 2017, 1, 6131.86, 6131.82) 请替换表名并重试 insert into yourTableName (CollegeID, DeptID, EmpID, Yr, Mnth, Act, Pred) values (234,
请帮助SQL替换表名并重试
insert into yourTableName (CollegeID, DeptID, EmpID, Yr, Mnth, Act, Pred) values (234, 34, 4, 2017, 1, 6131.86, 6131.82)
请替换表名并重试
insert into yourTableName (CollegeID, DeptID, EmpID, Yr, Mnth, Act, Pred) values (234, 34, 4, 2017, 1, 6131.86, 6131.82)
如果列名是静态的,您可能会使用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
是您的表名。如果列名是静态的,您可能会使用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
是您的表名。使用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
实现了横向连接,这比仅仅取消激活数据要强大得多。使用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
实现了横向连接,这比仅仅取消激活数据要强大得多。列名是静态的还是动态的?在Oracle中,您可以使用UNPIVOT,但我不知道它在SQL Server中是否可用。列名是静态的还是动态的?在Oracle中,您可以使用UNPIVOT,但我不知道它在SQL Server中是否可用。