Return just the last day of each month with SQL

前端 未结 9 677
执笔经年
执笔经年 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:55

    Here's how I just solved this. day_date is the date field, calendar is the table that holds the dates.

    SELECT cast(datepart(year, day_date) AS VARCHAR) 
    + '-' 
    + cast(datepart(month, day_date) AS VARCHAR) 
    + '-' 
    + cast(max(DATEPART(day, day_date)) AS VARCHAR) 'DATE'
    FROM calendar
    GROUP BY datepart(year, day_date)
        ,datepart(month, day_date)
    ORDER BY 1
    
    0 讨论(0)
  • 2020-12-30 06:04

    The easiest way I could find to identify if a date field in the table is the end of the month, is simply adding one day and checking if that day is 1.

    where DAY(DATEADD(day, 1, AsOfDate)) = 1
    

    If you use that as your condition (assuming AsOfDate is the date field you are looking for), then it will only returns records where AsOfDate is the last day of the month.

    0 讨论(0)
  • 2020-12-30 06:04

    This should work on Oracle DB

    select  distinct last_day(trunc(sysdate - rownum)) dt
        from dual
      connect by rownum < 430
       order by 1
    
    0 讨论(0)
提交回复
热议问题