【问题标题】:How do I insert some columns of a table into a new record with the same value of other columns?如何将表的某些列插入到与其他列具有相同值的新记录中?
【发布时间】:2020-04-17 11:42:18
【问题描述】:

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

示例值:

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

我试图取消透视列。但它没有用。

【问题讨论】:

  • 表没有“记录”,它们有列和行。希望您提出这个问题的原因是为了修复您的设计,因为它是非规范化的。另外,我建议看看升级路径; SQL Server 2008 完全不受支持,从去年 7 月就开始支持。

标签: sql sql-server tsql sql-server-2008


【解决方案1】:

您可以使用apply 取消透视数据:

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;

【讨论】:

  • @Madhukar。 . .是t
猜你喜欢
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多