ROW_NUMBER 没有给我正确的输出

ROW_NUMBER not giving me the correct output

我在 SQL 输出中获取正确的行号时遇到一些问题。我正在使用 ROW_NUMBER 函数,然后按 IDdate 进行分区,但似乎没有给我预期的结果。

SELECT 
    BCG.BudgetId
    ,CAST(BCG.StartOfPeriod AS DATE) AS StartOfPeriod
    ,ROUND(SUM(BCG.Charge),2) AS ExpenditureBudget
    ,ROUND(SUM(BCG.Consumption),2) AS ConsumptionBudget
    ,ROW_NUMBER() OVER (PARTITION BY BCG.BudgetId,BCG.StartOfPeriod ORDER BY BCG.StartOfPeriod ASC) AS rowNum
FROM B_BudgetCalGroup BCG 
WHERE BCG.BudgetId = 4940
GROUP BY BCG.BudgetId,StartOfPeriod

当前输出:

4940    2021-08-01  281495.36   2962365.8   1
4940    2021-09-01  276476.49   2943250.2   1
4940    2021-10-01  303252.47   3143659.7   1
4940    2021-11-01  292298.37   3090468.5   1
4940    2021-12-01  268543.23   2824347.8   1


预期输出:

4940    2021-08-01  281495.36   2962365.8   1
4940    2021-09-01  276476.49   2943250.2   2
4940    2021-10-01  303252.47   3143659.7   3
4940    2021-11-01  292298.37   3090468.5   4
4940    2021-12-01  268543.23   2824347.8   5

我是不是做错了什么?

发生这种情况是因为:

 PARTITION BY BCG.BudgetId,BCG.StartOfPeriod

每当 StartOfPeriod 不同时,这将重置行号,这是您的情况。所以替换为:

 PARTITION BY BCG.BudgetId

提示:在 OVER 子句的 PARTITION BYORDER BY 部分中不应该出现相同的字段。