Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return just the last day of each month with SQL

Tags:

sql

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 day of each month.

like image 867
Matt Avatar asked May 03 '11 06:05

Matt


People also ask

How do I get last day of month in SQL?

SQL Server EOMONTH() overview The EOMONTH() function returns the last day of the month of a specified date, with an optional offset. The EOMONTH() function accepts two arguments: start_date is a date expression that evaluates to a date. The EOMONTH() function returns the last day of the month for this date.

How do I get the first and last day of the month in SQL?

The logic is very simple. The first part @DATE-DAY(@DATE) results to the Last day of a previous month and adding 1 to it will result on the first day of current month. The second part EOMONTH(@DATE) makes use of SYSTEM function EOMONTH which results to the last day of the given date.

How do I get the first day of the month in SQL?

Below are the functions with logic explanation: 1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.


2 Answers

SQL Server (other DBMS will work the same or very similarly):

SELECT
  *
FROM
  YourTable
WHERE
  DateField IN (
    SELECT   MAX(DateField)
    FROM     YourTable
    GROUP BY MONTH(DateField), YEAR(DateField)
  )

An index on DateField is helpful here.

PS: If your DateField contains time values, the above will give you the very last record of every month, not the last day's worth of records. In this case use a method to reduce a datetime to its date value before doing the comparison, for example this one.

like image 197
Tomalak Avatar answered Oct 29 '22 12:10

Tomalak


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.

like image 24
Javier Rapoport Avatar answered Oct 29 '22 13:10

Javier Rapoport