问题描述
我有包含这样数据的源
+-------+-------+---------+--------------+----------------+-------------+--------------+
| ID | Name | Type | Product_Area | Product_status | Spare_value | Service_Time |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10001 | Motor | Product | Electrical | Active | | |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10002 | Fan | Product | Mechanical | Running | | |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10003 | Screw | Spare | | | 10 | |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10004 | Nut | Spare | | | 20 | |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10005 | Kit | Service | | | | 1 year |
+-------+-------+---------+--------------+----------------+-------------+--------------+
| 10006 | Oil | Service | | | | 6 months |
+-------+-------+---------+--------------+----------------+-------------+--------------+
我必须将其标准化并放入不同的表中。由于前 3 列对于所有类型都是通用的,因此 Product_Area
和 Product_status
将仅用于产品类型。同样,Spare_value
和 service_time
分别用于备件和服务。要求是创建一个 UID 并将其映射到其他表中,如下所示。
MASTER
+-----+-------+-------+---------+
| UID | ID | Name | Type |
+-----+-------+-------+---------+
| 1 | 10001 | Motor | Product |
| 2 | 10002 | Fan | Product |
| 3 | 10003 | Screw | Spare |
| 4 | 10004 | Nut | Spare |
| 5 | 10005 | Kit | Service |
| 6 | 10006 | Oil | Service |
+-----+-------+-------+---------+
PRODUCT
+-----+--------------+----------------+
| UID | Product_Area | Product_status |
+-----+--------------+----------------+
| 1 | Electrical | Active |
| 2 | Mechanical | Running |
+-----+--------------+----------------+
SPARE
+-----+-------------+
| UID | Spare_value |
+-----+-------------+
| 3 | 10 |
| 4 | 20 |
+-----+-------------+
SERVICE
+-----+--------------+
| UID | Service_Time |
+-----+--------------+
| 5 | 1 year |
| 6 | 6 months |
+-----+--------------+
我创建了一个 IDENTITY
并创建了第一个表 MASTER
,没有任何问题。但我不知道如何链接和创建其他表。我已经创建了 foreign key
但我仍然不知道如何获取 UID 并相应地映射 UID。请提出建议。
解决方法
试试 INSERT INTO SELECT 或 SELECT INTO :
INSERT INTO Product
SELECT IDENTITY(INT,1,1) AS UID,Product_Area,Product_status
FROM yourTable WHERE ID IN (10001,10002)
SELECT DISTINCT IDENTITY(int,Spare_value
INTO Spare
FROM yourTable
SELECT DISTINCT IDENTITY(int,Service_Time
INTO Service
FROM yourTable