如何使用 SQL 查询生成此数据列表?
how can I generate this list of data with a SQL query?
年
月
2021
1
2021
2
2021
3
2021
4
2021
5
2021
6
2021
7
2021
8
2021
9
2021
10
2021
11
2021
12
2022
1
2022
2
2022
3
2022
4
2022
5
2022
6
2022
7
2022
8
2022
9
2022
10
2022
11
2022
12
我可以得到一列,例如
SELECT * FROM generate_series(1,12) as month
但我找不到如何在它旁边生成另一列,而不是加入实际的 table.
您可以使用交叉连接:
SELECT y.year, m.month
FROM (SELECT 2020 + generate_series(1, 2) AS year) y
CROSS JOIN (SELECT generate_series(1, 12) AS month) m
ORDER BY y.year, m.month;
每个月创建一个日期列表:
select extract(year from dt) as "year",
extract(month from dt) as "month"
from generate_series(date '2021-01-01',
date '2022-12-31',
interval '1 month') as g(dt)
order by g.dt;
select
extract(year from d) "year",
extract(month from d) "month"
from generate_series ('2021-01-01', '2022-12-01', interval '1 month') as d;
您可以使用 CASE 语句
Select year.*,
CASE
WHEN year = 2021 THEN generate_series(1,12)
WHEN year = 2022 THEN generate_series(1,12)
END as month
from generate_series(2021,2022) as year
使用整数运算
select 2021 + m / 12 "year", m % 12 + 1 "month"
from generate_series(0, 23) as m
年 | 月 |
---|---|
2021 | 1 |
2021 | 2 |
2021 | 3 |
2021 | 4 |
2021 | 5 |
2021 | 6 |
2021 | 7 |
2021 | 8 |
2021 | 9 |
2021 | 10 |
2021 | 11 |
2021 | 12 |
2022 | 1 |
2022 | 2 |
2022 | 3 |
2022 | 4 |
2022 | 5 |
2022 | 6 |
2022 | 7 |
2022 | 8 |
2022 | 9 |
2022 | 10 |
2022 | 11 |
2022 | 12 |
我可以得到一列,例如
SELECT * FROM generate_series(1,12) as month
但我找不到如何在它旁边生成另一列,而不是加入实际的 table.
您可以使用交叉连接:
SELECT y.year, m.month
FROM (SELECT 2020 + generate_series(1, 2) AS year) y
CROSS JOIN (SELECT generate_series(1, 12) AS month) m
ORDER BY y.year, m.month;
每个月创建一个日期列表:
select extract(year from dt) as "year",
extract(month from dt) as "month"
from generate_series(date '2021-01-01',
date '2022-12-31',
interval '1 month') as g(dt)
order by g.dt;
select
extract(year from d) "year",
extract(month from d) "month"
from generate_series ('2021-01-01', '2022-12-01', interval '1 month') as d;
您可以使用 CASE 语句
Select year.*,
CASE
WHEN year = 2021 THEN generate_series(1,12)
WHEN year = 2022 THEN generate_series(1,12)
END as month
from generate_series(2021,2022) as year
使用整数运算
select 2021 + m / 12 "year", m % 12 + 1 "month"
from generate_series(0, 23) as m