如何在SQL Server中按分区(T-SQL)的最大秩()后添加一行

如何在SQL Server中按分区(T-SQL)的最大秩()后添加一行,sql,sql-server,Sql,Sql Server,也许这很简单,但我无法完成: 我有一张月值表。他们来自NAVISION,因此有客户签订了合同,并为该合同设定了月价值。我对数据进行了一点转换,以获得一个起点: 我编写此查询是为了检索数据: with NEW_CTE as ( SELECT End_of_Month_Date,Customer_No,Monthly_Contract_Value , case when customer_no<>lag(customer_No

也许这很简单,但我无法完成:

我有一张月值表。他们来自NAVISION,因此有客户签订了合同,并为该合同设定了月价值。我对数据进行了一点转换,以获得一个起点:

我编写此查询是为了检索数据:

with NEW_CTE as (

        SELECT  End_of_Month_Date,Customer_No,Monthly_Contract_Value
        , case 
            when customer_no<>lag(customer_No) over(order by customer_no,End_of_Month_Date) then NULL 
            else ISNULL(lag(Monthly_Contract_value) over(order by customer_no, End_of_Month_Date),0) 
            end as WertVormonat
        , case
            when customer_no<>lead(customer_No) over(order by customer_no,End_of_Month_Date) then NULL
            else ISNULL(lead(Monthly_Contract_value) over(order by customer_no, End_of_Month_Date),0) 
            end as WertFolgemonat
        ,rank() OVER(partition by Customer_No ORDER BY Customer_No,End_of_Month_Date) as RANKING
        FROM #contract_line)
我试图在客户的最大排名之后获得一个全新的行,因此在排名24之后的示例中,我需要一个包含以下数据的新行:

月末日期:应显示最大排名月份后的下一个月末

客户:应显示相同的客户

每月合约价值:0

WertVormonat:应显示前一个月的合同价值

WertFolgemonat:应显示NULL

但这还不是全部。仅当最大排名值的日期为过去时,该行才应显示。如果最后日期类似于2020年1月1日,则不应显示附加行

非常棘手-我知道。如果您有任何问题,请随时提问


谢谢你们的支持,伙计们

您可以使用选择按钮生成行:


您可以在此之前插入以插入行。您可以使用union all在select中进行合并。

请在SQL中定义此逻辑,因为只有您知道这些术语:应显示前一个月的合同价值。另外,这个临时表有主键吗?谢谢你的回复。在这种情况下,这意味着新行应显示排名24159.00的月度合同价值。在上面的示例中,我通过lag函数实现了这一点,因为您已经使用with语句,您可以重用别名来为实际数据和计算数据建立联合。比如说用新的。。。从NEW_CTE UNION ALL SELECT中选择*按客户分组数据、聚合数据等
select eomonth(dateadd(day, 1, end_of_month_date)),
       customer_no,
       . . .   -- your rules for the rest of the columns
from (select t.*,
             row_number() over (partition by customer_no order by ranking desc) as seqnum
      from t
     ) t
where seqnum = 1 and
      end_of_month_date < getdate();