如何将一个表中的记录插入到第二个表中

时间:2013-03-05 02:48:23

标签: sql sql-server sql-server-2005 unpivot

当前表未设置增长,我想将现有数据迁移到更适合扩展的表。让我解释一下:

当前表格设置如下:

+--------+---------------+----+----+----+------+-----------+
|     id | DateOfService | AM | MD | PM | RATE | CLIENT_ID |
+--------+---------------+----+----+----+------+-----------+
|      1 | 3/4/2013      |  1 |  0 |  0 |   10 |       123 |
|      2 | 3/5/2013      |  1 |  0 |  0 |   10 |       123 |
|      3 | 3/6/2013      |  1 |  0 |  0 |   10 |       123 |
|      4 | 3/5/2013      |  0 |  1 |  1 |   50 |       147 |
|      5 | 3/6/2013      |  1 |  1 |  1 |   25 |       189 |
+--------+---------------+----+----+----+------+-----------+

相反,我想设置我的表格如下:

+----------+---------------+---------------+-----------+
|     pkid | DateOfService | ServiceTypeID | CLIENT_ID |
+----------+---------------+---------------+-----------+
|        1 | 3/4/2013      |             1 |       123 |
|        2 | 3/5/2013      |             1 |       123 |
|        3 | 3/6/2013      |             1 |       123 |
|        4 | 3/5/2013      |             2 |       147 |
|        5 | 3/5/2013      |             3 |       147 |
|        6 | 3/6/2013      |             1 |       189 |
|        7 | 3/6/2013      |             2 |       189 |
|        8 | 3/6/2013      |             3 |       189 |
+----------+---------------+---------------+-----------+

ServiceTypeID表将是options表设置,如:

+-------------------+---------+
|     ServiceTypeID | Service |
+-------------------+---------+
|                 1 | AM      |
|                 2 | MD      |
|                 3 | PM      |
+-------------------+---------+

我需要帮助提出一个我可以运行的查询,它将选择并循环现有数据并填充我的新表。

2 个答案:

答案 0 :(得分:1)

您可以使用UNPIVOT函数将当前表从列转换为行。然后,您可以加入options表并将数据插入新表中。

UNPIVOT代码为:

select id,
  dateofservice,
  client_id,
  col, 
  value
from yourtable
unpivot
(
  value
  for col in (AM, MD, PM)
) unpiv
where value <> 0

请参阅SQL Fiddle with Demo

然后您将加入options表格以获得结果。您可以将此查询用于INSERT INTO新表:

-- INSERT INTO yourNewTable
select src.id as pkid,
  src.dateofservice,
  o.servicetypeid,
  src.client_id
from
(
  select id,
    dateofservice,
    client_id,
    col, 
    value
  from yourtable
  unpivot
  (
    value
    for col in (AM, MD, PM)
  ) unpiv
  where value <> 0
) src
inner join options o
  on src.col = o.service

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

由于您的选项表是“设置”,所以这样的事情会起作用:

INSERT INTO newtable
  SELECT id, dateofservice, 1, clientid
  FROM oldTable
  WHERE AM = 1
  UNION ALL
  SELECT id, dateofservice, 2, clientid
  FROM oldTable
  WHERE MD = 1
  UNION ALL
  SELECT id, dateofservice, 3, clientid
  FROM oldTable
  WHERE PM = 1

注意,我正在做同样的假设蓝色,你的示例表是错的,pk应该有值1,2,3,4,4,5,5,5

如果您希望该密钥是唯一的,那么只需将其定义为自动增量密钥,并且不要将其包含在此选择中。