如何根据yyyymmdd检索去年的当月和去年同月

时间:2018-06-13 23:38:38

标签: sql date reporting-services

有没有办法可以根据yyyymmdd检索今年和去年同月的月份?我的报告是比较去年和当月的数据。例如,如果yyyymmdd是20180613,那么我希望日期为20180601到20180613和20170601到20170613。

非常感谢您的所有建议和帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

在Oracle中 -

查询 -

select to_char(trunc(sysdate),'yyyymmdd') as y1, to_char(trunc(sysdate,'mm'),'yyyymmdd') as y2, to_char(trunc(sysdate) + interval '-1' year,'yyyymmdd') as y3, to_char(trunc(sysdate,'mm') + interval '-1' year,'yyyymmdd') as y4 from dual;

输出 -

"Y1","Y2","Y3","Y4"
"20180613","20180601","20170613","20170601"

答案 1 :(得分:1)

SQL Server

您可以尝试Convert(type,datetime,112)DATEADD

declare @tdate DATETIME= CONVERT(DATETIME, '20180613', 112) ;
select CONVERT(nvarchar(20), sDate1, 112) sDate1,
    CONVERT(nvarchar(20), eDate1, 112) eDate1,
    CONVERT(nvarchar(20), sDate2, 112) sDate2,
    CONVERT(nvarchar(20), eDate2, 112) eDate2
from (
    SELECT DATEADD(day, - DAY ( @tdate ) + 1 ,  @tdate) sDate1,
        @tdate eDate1,
        DATEADD(year,-1,DATEADD(day, - DAY ( @tdate ) + 1 ,  @tdate)) sDate2,
        DATEADD(year,-1,@tdate) eDate2
)T;

<强>结果:

sDate1               eDate1               sDate2               eDate2
-------------------- -------------------- -------------------- --------------------
20180601             20180613             20170601             20170613

Test DEMO Link