将数据从一个表中的列拆分为另一个表中的多个行
问题描述:
我有如下表格。如果我需要创建另一个表,如输出中所示,我该怎么做?将数据从一个表中的列拆分为另一个表中的多个行
CREATE TABLE TestTable
(JobID int, isAllowType1 bit, value1 int, isAllowType2 bit, value2 int)
;
INSERT INTO TestTable
(JobID, isAllowType1, value1, isAllowType2, value2)
VALUES
(1, 1, 11, 0, 111),
(2, 0, 22, 1, 222),
(3, 1, 33, 0, 333)
;
--output
JOBID isAllow Value Type
1 1 11 Type1
1 0 111 Type2
2 0 22 Type1
2 1 222 Type2
3 1 33 Type1
3 0 333 Type2
答
您可以在Type1和Type2记录单独使用查询,并使用union all
操作的结果结合起来:
SELECT jobid, isAllowType1 AS isAllow, value1 AS value, 'Type1' AS type
FROM testtable
UNION ALL
SELECT jobid, isAllowType1 AS isAllow, value1 AS value, 'Type2' AS type
FROM testtable
答
为了增加Mureinik的答案,你可以用UNION ALL
这样的结果创建一个新的表格:
select *
into new_table
from (
select JobID,
isAllowType1 isAllowType,
value1 value,
'Type1' Type
from TestTable
union all
select JobID,
isAllowType2,
value2,
'Type2'
from TestTable
) t
是否需要另一张桌子?你不能使用视图或存储过程吗? –
我正在重构一个有许多列的表,如isAllow1,isAllow2,isAllow3以及各种不同的值。 – GOMY