我有一张桌子:
table1(id int, count int)
现在我想得到一个包含table1&id;和一个增量编号列的结果。例如,table1有两行数据:
id计数 1 3 2 4
那么结果应该是
id nr
1 1
1 2
1 3
2 1
2 2
2 3
2 4
如何使用PostgreSQL或SQL Sever做到这一点?
答案 0 :(得分:1)
在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;
答案 1 :(得分:0)
如何使用postgresql或SQL Sever
您可以使用递归CTE在SQL Server中执行此操作。
WITH cteNumbers
AS (SELECT Id,
1 [Sequence],
[Count]
FROM Table1
UNION ALL
SELECT Id,
[Sequence] + 1,
[Count]
FROM cteNumbers
WHERE [Sequence] < [Count])
SELECT Id,
[Sequence]
FROM cteNumbers
ORDER BY 1,
2
OPTION (MAXRECURSION 0);