Skip to content

Commit ebd9db7

Browse files
committed
Merge branch 'main' of github.com:ankurbhambri/SQL-Learn
2 parents ea6ee8a + d0e7042 commit ebd9db7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Diff for: generate_series.sql

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Input
3+
4+
id | item | count
5+
----+------+-------
6+
1 | NYC | 2
7+
2 | KYC | 1
8+
3 | PYC | 4
9+
10+
Output
11+
12+
id | item
13+
----+------
14+
1 | NYC
15+
1 | NYC
16+
2 | KYC
17+
3 | PYC
18+
3 | PYC
19+
3 | PYC
20+
3 | PYC
21+
22+
*/
23+
24+
CREATE TABLE item_counts (
25+
id INT,
26+
item VARCHAR(3),
27+
count INT
28+
);
29+
30+
INSERT INTO item_counts (id, item, count) VALUES
31+
(1, 'NYC', 2),
32+
(2, 'KYC', 1),
33+
(3, 'PYC', 4);
34+
35+
-- Recursively
36+
with recursive cte as (
37+
select id, item, count, 1 as start
38+
from item_counts
39+
union all
40+
select id, item, count, 1 + start
41+
from cte
42+
where start < count
43+
)
44+
select id, item from cte order by id;
45+
46+
-- Using window function
47+
select id, item, generate_series(1, count) from item_counts;

0 commit comments

Comments
 (0)