[英]T-SQL for changing data from one table and insert into another table
我的基本表是這樣的:
ColumnA|ColumnB
---------------
A | C1
A | C2
A | C3
B | C1
B | C3
C | C4
我想從基表中讀取記錄並將其寫入下表:
ColumnA | C1 | C2 | C3 | C4
----------------------------
A | Y | Y | Y | N
B | Y | N | Y | N
C | N | N | N | Y
我不想使用光標,但是我不知道這是否可行。
謝謝
看一下PIVOT命令。 從那里可以執行INSERT INTO ... SELECT ...
SELECT ColumnA, [C1], [C2], [C3], [C4]
FROM (SELECT * FROM table) t
PIVOT
(
Count(ColumnB)
FOR ColumnB IN ([C1], [C2], [C3], [C4])
) As Pvt
一種(通常是快速的)方式是group by
:
insert NewTable (ColumnA, C1, C2, C3, C4)
select ColumnA
, IsNull(max(case when ColumnB = 'C1' then 'Y' end), 'N')
, IsNull(max(case when ColumnB = 'C2' then 'Y' end), 'N')
, IsNull(max(case when ColumnB = 'C3' then 'Y' end), 'N')
, IsNull(max(case when ColumnB = 'C4' then 'Y' end), 'N')
from OldTable
group by
ColumnA
另一種方法是子查詢,例如:
insert NewTable (ColumnA, C1, C2, C3, C4)
select src.ColumnA
, case when exists (select * from OldTable ot
where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C1')
then 'Y' else 'N' end
, case when exists (select * from OldTable ot
where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C2')
then 'Y' else 'N' end
, case when exists (select * from OldTable ot
where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C3')
then 'Y' else 'N' end
, case when exists (select * from OldTable ot
where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C4')
then 'Y' else 'N' end
from (
select distinct ColumnA
from OldTable
) src
或者,改編自克里斯潛水員的答案,與pivot
:
select ColumnA
, case when C1 > 0 then 'Y' else 'N' end C1
, case when C2 > 0 then 'Y' else 'N' end C2
, case when C3 > 0 then 'Y' else 'N' end C3
, case when C4 > 0 then 'Y' else 'N' end C4
from OldTable src
pivot (
count(ColumnB)
for ColumnB IN ([C1], [C2], [C3], [C4])
) pvt
假設您可以選擇所需的信息,則可以將插入內容作為選擇的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.