我希望在双表上使用oracle SQL显示从日期到日期之间的年份结果集
例如
如果我通过 - 从日期为1/1/1900和到日期为1/1/2000
然后它显示出来
只有几年
1900
1901
1902
-
-
2000
Run Code Online (Sandbox Code Playgroud)
这个问题分为两部分.生成日期范围非常简单:只需使用我在此演示的CONNECT BY技巧.
编辑
生成新年第一天的列表非常简单:
SQL> select add_months(to_date('01-jan-1900'), (level-1)*12) as year
2 from dual
3 connect by level <= 101
4 /
YEAR
---------
01-JAN-00
01-JAN-01
01-JAN-02
...
01-JAN-98
01-JAN-99
01-JAN-00
101 rows selected.
SQL>
Run Code Online (Sandbox Code Playgroud)
你只想要这些年?那么要么使用to_char(... , 'YYYY')它.或者切入追逐,只生成1900 - 2000年的数字列表.
您的请求中最棘手的部分是获得多少年.给出开始日期和偏移量而不是结束日期会更容易.无论如何......
SQL> select to_char(add_months(to_date('&&start_date'), (level-1)*12), 'YYYY') as year
2 from dual
3 connect by level <= ( to_number(to_char(to_date('&&end_date'), 'yyyy'))
4 -to_number(to_char(to_date('&&start_date'), 'yyyy')) ) + 1
5 /
Enter value for start_date: 01-jan-1900
old 1: select add_months(to_date('&&start_date'), (level-1)*12) as year
new 1: select add_months(to_date('01-jan-1900'), (level-1)*12) as year
Enter value for end_date: 01-jan-2000
old 3: connect by level <= ( to_number(to_char(to_date('&&end_date'), 'yyyy'))
new 3: connect by level <= ( to_number(to_char(to_date('01-jan-2000'), 'yyyy'))
old 4: -to_number(to_char(to_date('&&start_date'), 'yyyy')) ) - 1
new 4: -to_number(to_char(to_date('01-jan-1900'), 'yyyy')) ) - 1
YEAR
----
1900
1901
1902
...
1998
1999
2000
101 rows selected.
SQL>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |