sql - 将列值向左切换
问题描述
我有一个如下表:
Column A Column B Column C
---------- --------- -----------
1 1 2
4 3 4
3 null 2
12 12 12
15 7 7
8 9 6
null 2 2
null null 3
我需要将每列值从右向左移动,直到每列除了空值之外都有不同的值。输出必须是这样的:
Column A Column B Column C
---------- --------- -----------
1 2 null
4 3 null
3 2 null
12 null null
15 7 null
8 9 6
2 null null
3 null null
我怎样才能用最简单的方法做到这一点?
谢谢,
解决方案
unpivot、pivot 和条件排序的这种组合返回所需的输出:
with
nn as (
select id, col, case rn when 1 then val end val
from (
select id, col, val, row_number() over (partition by id, val order by col) rn
from (select rownum id, a, b, c from t)
unpivot (val for col in (a, b, c) ) ) ),
mov as (
select id, val,
row_number() over (partition by id
order by case when val is not null then col end ) rn
from nn )
select * from mov pivot (max(val) for rn in (1 a, 2 b, 3 c))
子查询nn
删除重复值,mov
基于条件排序的子查询将它们向上移动。然后枢轴将行转置为列,因为它们在第一步中未被转置。
推荐阅读
- python - TensorFlow 在看似中等大小的张量上内存不足
- arrays - Transform matrix to array in R
- javascript - How to search the length of the word in a txt file with jQuery?
- java - ArrayList Scanner 输入帮助 Java
- c# - 可以在不事先知道字段名称的情况下将文件提交到 ASP.NET Core 控制器操作吗?
- jmeter - JMeter 1 用户响应代码:非 HTTP 响应代码:java.net.ConnectionException 响应消息:非 HTTP 响应
- python - 使用卷积积分拟合指数衰减 -
- c++ - 将 DLL 添加到特定项目后出现 LNK2019 错误(通常工作正常)
- python - seasonal.seasonal_decompose 包中移动平均趋势的窗口长度是多少?
- c# - 在 DevExp 上更改 gridView 上的单元格数据