SSMS:如何 return 只为每个 month/year 而不是每一行的最后一行中的值?

SSMS: How to return only the value in the last row for each month/year instead of every row?

我使用的代码是 return month/year 内的所有日期,但我只希望它成为 return 最后日期行而不是所有每日行。

这是我正在使用的代码。

;WITH OIL_INDEX AS (
    SELECT PRODUCT_SYMBOL
    ,CONTRACT_MONTH
    ,CONTRACT_YEAR
    ,CONTRACT_DETAIL
    ,TRADEDATE
    ,SETTLE
    ,AVG(SETTLE) OVER (
            PARTITION BY CONTRACT_DETAIL, YEAR(TRADEDATE), MONTH(TRADEDATE)
            ORDER BY TRADEDATE 
            ROWS BETWEEN 29 PRECEDING and CURRENT ROW
        ) AS MA30
    ,YEAR(TRADEDATE) AS TRADEYEAR
    ,MONTH(TRADEDATE) AS TRADEMONTH
    ,DAY(TRADEDATE) AS TRADEDAY
    ,row_number() OVER(
     PARTITION BY CONTRACT_DETAIL, TRADEDATE
      ORDER BY TRADEDATE DESC) AS RowNum
     FROM Pricing.dbo.MasterReport$

)

SELECT PRODUCT_SYMBOL
    ,CONTRACT_MONTH
    ,CONTRACT_YEAR
    ,CONTRACT_DETAIL
    ,TRADEDATE
    ,TRADEYEAR
    ,TRADEMONTH
    ,TRADEDAY
    ,SETTLE
    ,MA30
    FROM OIL_INDEX
    WHERE RowNum = 1 AND PRODUCT_SYMBOL
    IN ('CL','CY','WJ')
    ORDER BY PRODUCT_SYMBOL ASC, CONTRACT_DETAIL ASC,TRADEYEAR ASC, TRADEMONTH ASC, TRADEDAY ASC

这是给出的结果。

这是我想要的。

我认为你只需要修改 window 函数的 PARTITION BY 子句:

之前:

ROW_NUMBER() OVER(
    PARTITION BY CONTRACT_DETAIL, TRADEDATE
    ORDER BY TRADEDATE DESC
) AS RowNum

之后:

ROW_NUMBER() OVER(
    PARTITION BY CONTRACT_DETAIL, YEAR(TRADEDATE), MONTH(TRADEDATE)
    ORDER BY TRADEDATE DESC
) AS RowNum

基本原理:您的分区子句为每个不同的 (CONTRACT_DETAIL, TRADEDATE ) 元组创建一个新组;这很容易生成很多组,每个组可能只有一条记录。相反,您希望按合约和 月份 进行分区,然后在每个组中按交易日期对记录进行排序。