T-SQL用于更改一个表中的数据并插入到另一个表中
我的基本表如下所示:T-SQL用于更改一个表中的数据并插入到另一个表中,sql,tsql,pivot,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 |
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
我不想使用光标,但我不知道这是否可行
谢谢假设您可以选择您喜欢的信息,那么您就可以根据选择的结果编写insert了。请查看该命令。从那里你可以做一个
插入到。。。选择…
SELECT ColumnA, [C1], [C2], [C3], [C4]
FROM (SELECT * FROM table) t
PIVOT
(
Count(ColumnB)
FOR ColumnB IN ([C1], [C2], [C3], [C4])
) As Pvt
一种(通常是快速的)方法是分组方式
:
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的回答改编,带有枢轴:
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
类似于透视表的东西,对吗?是的,我想,但我不知道如何使用这里C->C4应该是Y吗?你是想建立一个真值表,还是仅仅得到显示的输出?是的,现在它是正确的,我将把所有这些数据插入一个新表中(我不理解你所说的真值表)+1。如果要透视的列数在设计时已知,并且足够小,可以通过复制/粘贴这些子查询来管理,则这会更容易。在group by中,为什么要使用MAX?@oshin:必须指定一种方法,以便数据库聚合多行中的值。max()
中的表达式返回“Y”表示匹配,返回null表示不匹配。如果找到匹配的行,则其中的max()
为Y
,否则为null
。我使用分组方式解决方案,因为我比较了pivot运行时间与分组方式和分组方式更好。因此,我接受您的答案。谢谢,我只需要Y或N,我如何在这里使用case语句?我正在尝试case count(columnB)=0,然后是'N'或'Y'结束,但我遇到了错误:关键字'case'附近的语法不正确。@oshin:pivot在要求()
时不灵活。在我的答案中附加了一个pivot版本,可以解决这个问题,但如果您更喜欢pivot,请接受Chris Diver的答案:)您必须在select语句中的每个[Cx]
周围放置一个案例。