T-SQL用于从一个表更改数据并插入另一个表

时间:2010-07-16 15:13:46

标签: sql tsql pivot

我的基表就像:

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

我不想使用光标,但我不知道这是否可能。

由于

3 个答案:

答案 0 :(得分:2)

查看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 

答案 1 :(得分:1)

一种(通常是快速的)方式是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

或者改编自Chris Diver的答案,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

答案 2 :(得分:0)

假设您可以选择您喜欢的信息,那么您可以将该插入作为该选择的结果。