Return just the last day of each month with SQL

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

    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.

提交回复
热议问题