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
You seed to want May 31st based on some strange date arithmetic -- presumably, some sort of fiscal year.
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.
In SQL Server, this would be:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.