在SQL SERVER 2014中。
SQL查询
我想用FCD和Assembly两个表创建表FCD_Assembly。
我的桌子是这样的:
===================== ||组装表|| ========================
+-------------+-------+-------+-------+-------+-------+
| ID_Assembly | Col_1 | Col_2 | Col_3 | Col_4 | Col_5 |
+-------------+-------+-------+-------+-------+-------+
| 1200 | 0 | 0 | 1 | 0 | 0 |
| 1201 | 1 | 0 | 0 | 0 | 1 |
| 1202 | 0 | 1 | 0 | 0 | 0 |
| 1203 | 0 | 0 | 0 | 1 | 0 |
| 1204 | 0 | 1 | 0 | 0 | 1 |
===================== || FCD表|| ========================
+--------+--------+------+
| ID_FCD | Tittle | type |
+--------+--------+------+
| 1 | Col_1 | F |
| 2 | Col_2 | F |
| 3 | Col_3 | F |
| 4 | Col_4 | C |
| 5 | Col_5 | D |
===================== || FCD_Assembly表格|| ========================
+-------------+-------------+
| ID_FCD | ID_Assembly |
+-------------+-------------+
| 3 | 1200 |
| 1 | 1201 |
| 5 | 1201 |
| 2 | 1202 |
| 4 | 1203 |
| 2 | 1204 |
| 5 | 1204 |
我要创建表FCD_Assembly
感谢您的帮助:)
答案 0 :(得分:1)
您需要对unpivot
表使用Assembly
,让列名成为行值,然后对join
表执行FCD
。
我会用CROSS APPLY
来做unpivot
。
SELECT f.ID_Assembly,t1.id
FROM (
select v.* from Assembly CROSS APPLY
(
VALUES
(ID_Assembly,Col_1,'Col_1'),
(ID_Assembly,Col_2,'Col_2'),
(ID_Assembly,Col_3,'Col_3'),
(ID_Assembly,Col_4,'Col_4'),
(ID_Assembly,Col_5,'Col_5')
) v (id,val,Title)
WHERE v.val <> 0
)t1 JOIN FCD f on t1.Title = f.Tittle
结果
ID_FCD ID_Assembly
3 1200
1 1201
5 1201
2 1202
4 1203
2 1204
5 1204