将两个表转换为单个表

时间:2013-06-18 13:49:14

标签: sql sql-server

我有这两个表:

+-------------+--------+      +----+-------+
| employee_id | val_id |      | id | value |
+-------------+--------+      +----+-------+
|         123 |      1 |      |  1 |     A |
+-------------+--------+      +----+-------+
|         123 |      2 |      |  2 |     B |
+-------------+--------+      +----+-------+
|         123 |      3 |      |  3 |     C |
+-------------+--------+      +----+-------+

预期结果

+-------------+-------+-------+-------+ 
| employee_id | val_1 | val_2 | val_3 | ...
+-------------+-------+-------+-------+ 
|         123 |     A |     B |     C |

请你帮帮我

2 个答案:

答案 0 :(得分:0)

  1. 在第一个表中创建值列
  2. 按更新子句更新'value'列(您可以使用subselect选择值)
  3. DROP val_id列
  4. DROP第二张表
  5. 桌子有多大?

答案 1 :(得分:0)

使用join和pivot。这将提供所需的结果

SELECT * FROM(
SELECT employeeID,'val_'+CAST(a.val_id AS VARCHAR(2)) val_id ,value 
FROM table1 a INNER JOIN table2 b ON a.val_id=b.val_id
) AS ss
PIVOT
(
    MAX(value)
    FOR [val_id] IN ([val_1],[val_2],[val_3])
)AS pivott