SQL如何对齐行中的数据点范围?

时间:2017-02-17 08:39:07

标签: sql oracle window-functions

假设拥有数据集:

$p_name = "Berta";

$query = $articles->find()->contain([
    'Comments' => function ($q) {
       return $q
            ->select(['name'])
            ->where(['Comments.name' => $p_name]);
    }
]);

我们发现与with data_table(title, x) as ( select 'a', 1 from dual union all select 'a', 3 from dual union all select 'a', 4 from dual union all select 'a', 5 from dual union all select 'b', 1 from dual union all select 'b', 2 from dual union all select 'b', 3 from dual union all select 'b', 6 from dual ) select * from data_table; TITLE | X ----------- a 1 a 3 a 4 a 5 b 1 b 2 b 3 b 6 a相关的点数不同。

如何对齐b列中的值,以便两个群组具有相同的点,填补X的空白?

预期结果是:

NULL

我得到的直接解决方案是

 TITLE | X
-----------
  a     1
  a    NULL
  a     3
  a     4
  a     5
  a    NULL
  b     1
  b     2
  b     3
  b    NULL
  b    NULL
  b     6

正如with data_table(title, x) as ( select 'a', 1 from dual union all select 'a', 3 from dual union all select 'a', 4 from dual union all select 'a', 5 from dual union all select 'b', 1 from dual union all select 'b', 2 from dual union all select 'b', 3 from dual union all select 'b', 6 from dual ), all_points(x) AS ( select distinct x from data_table ), all_titles(title) AS ( select distinct title from data_table ), aligned_data(title, x) as ( select t.title, p.x from all_points p cross join all_titles t ) select ad.title, dt.x from aligned_data ad left join data_table dt on dt.title = ad.title and dt.x = ad.x order by ad.title, ad.x; cross join定义中的aligned_data是瓶颈,可能会破坏有价值数据集的性能。

我想知道这个任务是否可以更优雅地解决。也许可以提出一个带窗口函数的技巧。

0 个答案:

没有答案