简体   繁体   English

如何将日期数字四舍五入到SQL中最接近的月份?

[英]How Do I Round Date Figures to the nearest Month in SQL?

2015-01-28T01:45:31.000Z 2015-01-28T01:45:31.000Z

I want to round the column values for date to the nearest month. 我想将日期的列值四舍五入到最接近的月份。 Is there a way I can do that with a SELECT statement? 有什么方法可以使用SELECT语句吗?

select date_format(date_field, '%Y-%m') as date_rounded

The statement below will round the date to the 1st of the current month if the day is less than 16, otherwise the date will be rounded to the 1st of the next month. 如果日期小于16,则下面的语句将日期四舍五入到当前月份的第一天,否则将日期四舍五入到下一个月的第一天。

SELECT CASE 
         WHEN date_format(myDate, '%d') < '16' THEN
           date_format(myDate, '%Y-%m-01')
         ELSE
           date_format( DATE_ADD(myDate, INTERVAL 1 MONTH) , '%Y-%m-01')
         END as 'date_rounded'
  FROM my_table;

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

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