我如何使用 WHERE 子句对 PARTITION BY 进行 RANK()

How can I RANK() OVER PARTITION BY with a WHERE Clause

我需要在 table 中做 2 个等级,一个用于所有行,另一个用于总产量大于零的地方。有没有办法用等级函数来做到这一点?

SELECT 
       LocationNumber
      ,[Date]
      ,Oil+Gas+Water as [TotalFluid]
      ,sum(Oil + Gas + Water ) over (partition by [LocationNumber] order by [Date] asc) as [CumTotalFluid]
      ,rank() over (partition by [LocationNumber] order by [Date] asc) as TABLE_DAY
      ,rank() over (partition by [LocationNumber] order by [Date] asc WHERE CumTotalFluid > 0) as Prod_DAY

FROM DV

您可以使用条件逻辑:

SELECT LocationNumber, [Date], (Oil+Gas+Water) as [TotalFluid],
       sum(Oil + Gas + Water ) over (partition by [LocationNumber] order by [Date] asc) as [CumTotalFluid],
       rank() over (partition by [LocationNumber] order by [Date] asc) as TABLE_DAY
       (CASE WHEN CumTotalFluid > 0
             THEN rank() over (partition by [LocationNumber], CASE WHEN CumTotalFluid > 0 THEN 1 ELSE 0 END order by [Date] asc
                              ) 
        END) as Prod_DAY
FROM DV;

外部 case 只有 returns 条件为真的值。 partition by中的case把数据分成两组(多),所以排名是正确的。