[英]Split data from columns in one table to multiple rows in another
我有下表。 如果需要創建輸出中所示的另一個表,該怎么辦?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.