sql - 如何在 SQL 中创建从 1 到数字的递增数字列

标签 sql postgresql

我有一张表:

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;

在线示例:http://rextester.com/KNQG24769

关于sql - 如何在 SQL 中创建从 1 到数字的递增数字列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43703064/

相关文章:

sql - 什么是 'identity increment' 表的 'Orders' 的好值

c# - asp.net core 2.0身份 Entity Framework 用户未保存

mysql - sql查询以查找具有与会者人数的事件的所有 session

sql - 有没有安全的方法来转换 SQL 日期时间?

sql - 如何将单个选择插入到两个不同的表中?

php - 选择要进行 sql 和 Sum 的日期

python - 使用 .format() 时出现 psycopg2 编程错误

sql - 使用 Node.js 客户端和连接池在 Postgres 中最快的查询 - 存储函数或准备好的语句?

postgresql - 列 "migrations.id"具有不受支持的类型 "serial"

laravel - 如何在 Laravel 中收听 Postgres 监听/通知?