Return just the last day of each month with SQL

前端 未结 9 861
执笔经年
执笔经年 2020-12-30 05:22

I have a table that contains multiple records for each day of the month, over a number of years. Can someone help me out in writing a query that will only return the last d

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 05:40

    In SQL Server, this is how I usually get to the last day of the month relative to an arbitrary point in time:

    select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
    

    In a nutshell:

    1. From your reference point-in-time,
    2. Add 1 month,
    3. Then, from the resulting value, subtract its day-of-the-month in days.

    Voila! You've the the last day of the month containing your reference point in time.

    Getting the 1st day of the month is simpler:

    select dateadd(day,-(day(current_timestamp)-1),current_timestamp)
    
    1. From your reference point-in-time,
    2. subtract (in days), 1 less than the current day-of-the-month component.

    Stripping off/normalizing the extraneous time component is left as an exercise for the reader.

提交回复
热议问题