如何根据字段获取每个月的最后一天

Ezz*_*zzy 2 sql sql-server sql-server-2008

SELECT [ItemKey]
  ,[Location]
  ,[QtyOnHand]
  ,[UpdatedOnHandQty]
  ,AffectedDate
  FROM [Test].[dbo].[INCos]
  where ItemKey = '20406' 
  order by ItemKey, year(AffectedDate)
Run Code Online (Sandbox Code Playgroud)

结果如下:

ItemKey UpdatedOnHandQty    AffectedDate
20406   1594.03            2013-12-27 00:00:00.000
20406   78.975            2014-09-15 00:00:00.000
20406   1401.975          2014-09-26 00:00:00.000
20406   512.261           2014-10-20 00:00:00.000
20406   849.928         2014-01-06 00:00:00.000
20406   842.132       2014-01-09 00:00:00.000
20406   1283.132      2014-02-05 00:00:00.000
20406   539.03        2014-02-11 00:00:00.000
20406   980.03       2014-05-07 00:00:00.000
20406   486.183      2014-05-12 00:00:00.000
20406   927.183      2014-06-03 00:00:00.000
20406   917.86       2014-06-27 00:00:00.000
20406   927.043     2014-07-18 00:00:00.000
20406   432.209     2014-07-18 00:00:00.000
20406   1314.209    2014-07-29 00:00:00.000
Run Code Online (Sandbox Code Playgroud)

我想要的是每年只记录每月最后一天的记录.我已经看到很多解决方案,我可以根据GetDate()获得每个月的最后一天,但我不需要.我只需要根据AffectedDate字段提取每年每月的最后一条记录.

Joh*_*tti 5

一个快速选项是与Row_Number()一起使用WITH TIES子句

Select Top 1 with Ties * 
 From  YourTable
 where ItemKey = '20406' 
 Order by Row_Number() over (Partition by ItemKey,Year(AffectedDate),Month(AffectedDate) Order by AffectedDate Desc)
Run Code Online (Sandbox Code Playgroud)

返回

ItemKey UpdatedOnHandQty    AffectedDate
20406   1594.03             2013-12-27 00:00:00.000
20406   842.132             2014-01-09 00:00:00.000
20406   539.03              2014-02-11 00:00:00.000
20406   486.183             2014-05-12 00:00:00.000
20406   917.86              2014-06-27 00:00:00.000
20406   1314.209            2014-07-29 00:00:00.000
20406   1401.975            2014-09-26 00:00:00.000
20406   512.261             2014-10-20 00:00:00.000
Run Code Online (Sandbox Code Playgroud)