sql—如何基于计数复制表中的行

yfjy0ee7  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(360)

我在oracle数据库中有这样一个频率表,其中n是每次出现的次数:

  1. weight | N
  2. 12 | 3
  3. 34 | 2
  4. 56 | 1

是否可以将每行的数目乘以出现的数目,得到如下表格:

  1. weight | N
  2. 12 | 1
  3. 12 | 1
  4. 12 | 1
  5. 34 | 1
  6. 34 | 1
  7. 56 | 1

谢谢您,

mu0hgdu0

mu0hgdu01#

可以使用数字生成器、递归查询、xmltable。有很多选择。例如:

  1. with t as (select weight, '1 to '||n list from frequency)
  2. select weight, 1 from t, xmltable(list)

  1. with r(weight, n) as (select weight, n from frequency union all
  2. select weight, n-1 from r where n-1 > 0)
  3. select weight, 1 from r order by weight

D小提琴

r6hnlfcb

r6hnlfcb2#

一种简单的方法是递归cte:

  1. with recursive cte as (
  2. select weight, n
  3. from t
  4. union all
  5. select weight, n - 1
  6. from t
  7. where n > 1
  8. )
  9. select weight, 1 as n
  10. from cte;

请注意,尽管递归cte是标准的一部分,但是语法中有一些变化,因此您的数据库可能有点不同。
编辑:
在旧版本的oracle中,您可以生成所需的数字,然后生成数据:

  1. with n as (select level as n
  2. from (select max(n) as n from t) n
  3. connect by level <= n
  4. )
  5. select t.weight, 1 as n
  6. from t join
  7. n
  8. on n.n <= t.n;

新版本的oracle支持递归cte。

展开查看全部

相关问题