1

当前表不是为增长而设置的,我想将现有数据迁移到更适合扩展的表中。让我解释:

当前表设置如下:

+--------+---------------+----+----+----+------+-----------+
|     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      |
+-------------------+---------+

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

4

2 回答 2

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

然后您将加入您的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

于 2013-03-05T02:56:47.537 回答
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

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

于 2013-03-05T03:08:26.453 回答