我有两张桌子表1和2,如下图所示。我需要在结果表3中为表A中存在A和其对应的Act_rid的行插入Std_rid。我只在这里使用示例。我很困惑这里是否使用pivot或unpivot。任何帮助赞赏。感谢
Table 1
----------
G_Standard N_Standard Skill One_for_all Am_Water B2Future Std_rid
ELW.6 Lit.W.K.6 Writing A 1
ELW.8 Lit.W.K.8 Writing A 2
ELW.7 Lit.W.K.7 Writing A 3
Table 2
----------
Act_rid Act_Desc date createdby
3 Am_Water 2/4/15 sys
6 B2Future 2/4/15 sys
1 One_for_all 2/14/15 sys
Output Result Table 3
----------
ID Std_rid Act_rid
1 1 3
2 2 6
3 3 1
答案 0 :(得分:1)
这是一个UNPIVOT。 UNPIVOT将列转换为行。
;WITH Unpivot_Table_1 AS (
SELECT Std_rid,
Act_Desc
FROM [Table 1]
UNPIVOT (Value FOR Act_Desc IN ([One_for_all],[Am_Water],[B2Future])) u
WHERE u.Value = 'X'
)
SELECT ROW_NUMBER() OVER(ORDER BY t1.Std_rid) AS ID,
t1.Std_rid,
t2.Act_rid
FROM Unpivot_Table_1 t1
JOIN [Table 2] t2
ON t2.Act_Desc = t1.Act_Desc;
我希望这是数据集成的东西。否则,你们都需要拍摄任何设计的人。
测试数据:
CREATE TABLE dbo.[Table 1]
(
Std_rid INT NOT NULL PRIMARY KEY,
One_for_all VARCHAR(1),
Am_Water VARCHAR(1),
B2Future VARCHAR(1)
);
INSERT INTO dbo.[Table 1] (Std_rid,One_for_all,Am_Water,B2Future)
VALUES
(1,NULL,'X',NULL),
(2,NULL,NULL,'X'),
(3,'X',NULL,NULL);
CREATE TABLE dbo.[Table 2]
(
Act_rid INT NOT NULL PRIMARY KEY,
Act_Desc VARCHAR(30)
);
INSERT INTO dbo.[Table 2] (Act_rid,Act_Desc)
VALUES
(3,'Am_Water'),
(6,'B2Future'),
(1,'One_for_all');