首页 > 解决方案 > 如何将表的某些列插入到与其他列具有相同值的新记录中?

问题描述

我有一个包含以下示例值的阶段表。如果有多个名称或城市以及其他列,我想创建一条新记录。我怎样才能做到这一点?

样本值:

id  pr  name1   city1   name2   city2   name3   city3   state   country
c1  p1  name11  city11  name21  city21  name31  city31  s1      country1
c2  p2  name12  city12  NULL    city22  NULL    NULL    s2      country2
c3  p3  name13  city13  NULL    NULL    NULL    NULL    s3      country3
c4  p4  name14  city14  name24  city24  name34  NULL    s4      country4
c5  p4  name15  city15  name25  city25  NULL    NULL    s5      country5

预期输出:

id  pr  name    city    state   country
c1  p1  name11  city11  s1      country1
c1  p1  name21  city21  s1      country1
c1  p1  name31  city31  s1      country1
c2  p2  name12  city12  s2      country2
c2  p2  NULL    city22  s2      country2
c3  p3  name13  city13  s3      country3

我试图取消旋转列。但它没有用。

标签: sqlsql-servertsqlsql-server-2008

解决方案


您可以使用applyunpivot 数据:

select t.id, t.pr, v.name, v.city, t.state, t.country
from t cross apply
     (values (t.name1, t.city1), (t.name2, t.city2), (t.name3, t.city3)
     ) v(name, city)
where v.name is not null;

推荐阅读