简体   繁体   English

如何基于yyyymmdd检索当年的月份和去年的同一个月

[英]how to retrieve month current year and same month last year based on yyyymmdd

is there a way I can retrieve the month this year and same month last year based on yyyymmdd? 有什么方法可以根据yyyymmdd检索今年的月份和去年的同一月? My report is comparing data from last year month and current year month. 我的报告正在比较去年月份和当年月份的数据。 For example if yyyymmdd is 20180613 then I would like to have dates 20180601 to 20180613 and 20170601 to 20170613. 例如,如果yyyymmdd为20180613,那么我想输入日期20180601至20180613和20170601至20170613。

Would really appreciate all your advice and help I can get. 非常感谢您的所有建议和帮助。

Thank you! 谢谢!

In Oracle - 在Oracle中-

Query - 查询-

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;

Output - 输出-

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

SQL Server SQL服务器

You can try Convert(type,datetime,112) and DATEADD 您可以尝试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;

Result: 结果:

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

Test DEMO Link 测试演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据年份和月份动态检索一年前(下个月)到当前月末的所有数据 - How to dynamically retrieve all data from a year ago (Next Month) till the end of current Month based on year and month 如何根据当前月份和年份从表中获取上个月的数据? - How to get last one month's data from a table based on current month and year? 如何根据SQL中的上个月平均值和去年同月平均值计算值 - How to calculate value based on average of previous month and average of same month last year in SQL 获取最近 2 个月(当年)和上个月(去年)的记录 - Get records of last 2 months (current year), and last month(last year) SQL:选择去年的当前月份 - SQL: Selecting current month last year 去年当前月份的SQL代码 - SQL code for CUrrent Month Last Year 如何在 Hive 中查找上一年特定月份的销售额高于或不高于当年同月 - How to find the previous year particular month sale is higher or not compared to the same month of current year in Hive 根据上个月开始年度 - Get Start of Year based on Last Month 如果年份和月份是单独的列,则获取当前和上个月的数据, - Get current and last month data if year and month are separate columns, 如何根据字段获取每个月的最后一天 - How to get the last day for each month in a distinct year based on a field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM