简体   繁体   English

基于SQL中日期范围的动态创建设置日期的方法

[英]Dynamic way to create a set date based on a range of dates in SQL

I'm trying to create a set date based on a range in order to create a set for visualizations. 我正在尝试根据范围创建一个设置日期,以便为可视化创建一个设置。 This is awfully repetitive and not future proof. 这是非常重复的,不是未来的证明。 Does anyone have any ideas on how to simplify this? 有没有人对如何简化这个有任何想法?

Select CASE WHEN date BETWEEN '2010-08-01 00:00:00' AND '2011-07-31 12:59:59'
        THEN '2011-05-31 00:00:00'
    WHEN date BETWEEN '2011-08-01 00:00:00' AND '2012-07-31 12:59:59'
        THEN '2012-05-31 00:00:00'
    WHEN date BETWEEN '2012-08-01 00:00:00' AND '2013-07-31 12:59:59'
        THEN '2013-05-31 00:00:00'
    WHEN date BETWEEN '2013-08-01 00:00:00' AND '2014-07-31 12:59:59'
        THEN '2014-05-31 00:00:00'
    WHEN date BETWEEN '2014-08-01 00:00:00' AND '2015-07-31 12:59:59'
        THEN '2015-05-31 00:00:00'
    WHEN date BETWEEN '2015-08-01 00:00:00' AND '2016-07-31 12:59:59'
        THEN '2016-05-31 00:00:00'
    WHEN date BETWEEN '2016-08-01 00:00:00' AND '2017-07-31 12:59:59'
        THEN '2017-05-31 00:00:00'
    WHEN date BETWEEN '2017-08-01 00:00:00' AND '2018-07-31 12:59:59'
        THEN '2018-05-31 00:00:00'
    WHEN date BETWEEN '2018-08-01 00:00:00' AND '2019-07-31 12:59:59'
        THEN '2019-05-31 00:00:00'
    WHEN date BETWEEN '2019-08-01 00:00:00' AND '2020-07-31 12:59:59'
        THEN '2020-05-31 00:00:00'
    END AS modifiedDate, 

FROM table1 从表1

You seed to want May 31st based on some strange date arithmetic -- presumably, some sort of fiscal year. 您可能希望基于某种奇怪的日期算法(可能是某种会计年度)来确定5月31日。

This can all be calculated using date arithmetic. 所有这些都可以使用日期算术来计算。 Without a database tag, it is hard to specify the correct syntax. 没有数据库标签,很难指定正确的语法。 But, the idea is: 但是,这个想法是:

select (date '2011-05-31' +
        (extract(year from date + interval '5 month') - 2011) * interval '1 year'
       )

This is expressed in ISO/ANSI SQL, but the idea can be expressed in any database -- although any given database might have other approaches as well. 这用ISO / ANSI SQL表示,但是这个想法可以在任何数据库中表示-尽管任何给定的数据库也可能具有其他方法。

In SQL Server, this would be: 在SQL Server中,这将是:

select dateadd(year,
               (extract(year from date + interval '5 month') - 2011),
               '2011-05-31'
              )

Got this from another site before you guys answered, which worked perfectly: 在您回答之前,已从另一个站点获得了此功能,效果很好:

Case when month(date)>=8 then datefromparts(year(date)+1,5,31) 
        when month(date)<8 then datefromparts(year(date),5,31) 
    end as modifiedDate

Thanks for your answers too. 也感谢您的回答。 Helped me on a couple of other issues I was having. 帮助我解决了其他一些问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM