如何将列联表插入SQL Server数据库?

时间:2012-03-06 16:38:48

标签: sql-server

我有一个列联表,并希望将其插入到SQL Server数据库中:

列联表:

|      | soccer  | football  | basketball  |
+------+---------+-----------+-------------
|  Max |    x    |           |      x      |
|  Mary|    x    |           |             |
|  Tim |         |           |      x      |
+------+---------+-----------+-------------

应通过T-SQL INSERT转换为:

| name | sports  | 
+------+---------+
|  Max | soccer  |
|  Max | basketball 
| Mary | soccer  |   
| Tim  | basketball   
+------+---------+

现在可以在SQL Server中使用SQL吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

如果这是xls数据,您可以运行直接脚本将相同的数据插入SQL Server表。然后,您可以为每项运动运行不同的INSERT查询,以使其符合您所需的格式,并删除原始表格。

假设原始表中的第一列被称为Name

INSERT INTO [TableB] (Name, Sports)
SELECT Name, 'Soccer'
FROM [TableA]
WHERE Soccer=1

INSERT INTO [TableB] (Name, Sports)
SELECT Name, 'Football'
FROM [TableA]
WHERE Football=1

INSERT INTO [TableB] (Name, Sports)
SELECT Name, 'Basketball'
FROM [TableA]
WHERE Basketball=1