简体   繁体   English

T-SQL,用于更改一个表中的数据并插入到另一个表中

[英]T-SQL for changing data from one table and insert into another table

My base table is like: 我的基本表是这样的:

ColumnA|ColumnB
---------------
   A   |  C1
   A   |  C2
   A   |  C3
   B   |  C1
   B   |  C3
   C   |  C4

I want to read records from the base table and write it into the below table: 我想从基表中读取记录并将其写入下表:

ColumnA | C1 | C2 | C3 | C4
----------------------------
   A    | Y  |  Y | Y  | N
   B    | Y  |  N | Y  | N
   C    | N  |  N | N  | Y

I don't want to use a cursor, but I don't know if that's possible or not. 我不想使用光标,但是我不知道这是否可行。

Thanks 谢谢

Have a look at the PIVOT command. 看一下PIVOT命令。 From there you can do a INSERT INTO ... SELECT ... 从那里可以执行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 

One (usually fast) way would be group by : 一种(通常是快速的)方式是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

Another way is subqueries, like: 另一种方法是子查询,例如:

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

Or, adapted from Chris Diver's answer, with pivot : 或者,改编自克里斯潜水员的答案,与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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM