我有一张表:
table1(id int, count int)
现在我想得到一个结果,其中包含表 1 的 ID 和一个从 1 到 count 的增量数字列。例如table1有两行数据:
身份证号码 1 3 2 4
那么结果应该是
id nr
1 1
1 2
1 3
2 1
2 2
2 3
2 4
我如何使用 PostgreSQL 或 SQL Sever 来做到这一点?
最佳答案
在 Postgres 中你可以使用 generate_series()
select t1.id, g.nr
from table1 t1
cross join lateral generate_series(1, t1.count) as g(nr)
order by t1.id, g.nr;
递归 CTE 也适用于 Postgres:
WITH recursive cte as (
SELECT id, count, 1 as nr
FROM table1
UNION ALL
SELECT id, count, nr + 1
from cte
WHERE nr < count
)
SELECT id, nr
FROM cte
ORDER BY id, nr;
关于sql - 如何在 SQL 中创建从 1 到数字的递增数字列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43703064/