sql - 如何将表的某些列插入到与其他列具有相同值的新记录中?
问题描述
我有一个包含以下示例值的阶段表。如果有多个名称或城市以及其他列,我想创建一条新记录。我怎样才能做到这一点?
样本值:
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
我试图取消旋转列。但它没有用。
解决方案
您可以使用apply
unpivot 数据:
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;
推荐阅读
- reactjs - 在 React 中呈现可选组件列表
- php - 如何通过配置定义数据的路由来使 auth() 的不同页面注册页面
- java - 公历日期至今
- java - 春季LDAP | 登录并获取会员
- javascript - 如何从 woocommerce 订单的按钮值创建链接
- ios - StackView 内 UICollectionView 的动态高度
- java - 使用 OPC UA Java Legacy 连接到 Matrikon 服务器
- sql - 在查询中查找 SQL 表
- node.js - 通过nodejs angular4或express为http请求设置长超时
- java - 如何在 AWS 中设置 HBase?