如何在oraclesql中获得两个日期之间的月份

ctehm74n  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(300)

我需要得到两次约会之间的月份数。例如,在这些日期之间:“03/03/2020-06/06/2020”我需要类似“(03,04,05,06)”的内容。

kupeojn6

kupeojn61#

试试这个 DATEDIFF 实现这一点的功能:

SELECT RIGHT(CONCAT('00',DATEDIFF(MONTH,'03/06/2020','06/06/2020')) ,2)
h79rfbju

h79rfbju2#

我是一名sql server程序员,如果您的问题是关于sql server的,那么解决方案如下:

;WITH cte AS
(
SELECT TOP (DATEDIFF(MONTH, '2020-03-03', '2020-06-06') + 1)
Format(DateAdd(MONTH, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, '2020-03-03'), 'MM', 
'en-US') AS MonthNumber
FROM    sys.all_objects a
)
SELECT '(' + String_Agg(MonthNumber, ', ') + ')' AS Result
FROM cte;

我已经测试了上面的代码,它会根据需要返回“(03,04,05,06)”。我尽了最大努力将上述sql server解决方案重写为oracle sql,但目前无法对其进行测试。你可以试试:

WITH cte AS
(
SELECT TOP (MONTHS_BETWEEN (TO_DATE('06/06/2020','DD/MM/YYYY'),
                            TO_DATE('03/03/2020','DD/MM/YYYY') ) + 1)
TO_CHAR(ADD_MONTHS(ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, TO_DATE('03/03/2020','DD/MM/YYYY')), 'MM') 
AS MonthNumber
FROM sys.all_objects a
)
SELECT '(' + LIST_AGG(MonthNumber, ', ') + ')' AS Result
FROM cte;
k7fdbhmy

k7fdbhmy3#

对于oracle:

SQL> column months format a24
SQL> select banner from v$version where rownum=1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> select '(' || listagg(m, ',') || ')' as months
  2  from (
  3   select
  4   extract(month from to_date('03/03/2020')) m1,
  5   extract(month from to_date('06/06/2020')) m2
  6   from dual) mm
  7  inner join (
  8   select level as m
  9   from dual
 10   connect by level <= 12) l
 11  on m >= m1 and m <=m2
 12  ;

MONTHS
------------------------
(3,4,5,6)

SQL>

相关问题