简体   繁体   English

如何使用WHERE子句在分区上进行RANK()

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

I need to do 2 ranks in a table, one for all rows and one where Total Cum Production is greater than zero. 我需要在一张表中进行2个排名,一个列用于所有行,一个列中的“总生产总值”大于零。 Is there any way to do that with a Rank Function? 有什么办法可以通过排名函数做到这一点?

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

You can use conditional logic: 您可以使用条件逻辑:

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;

The outer case only returns values where the condition is true. case仅返回条件为真的值。 The case in the partition by divides the data into two (more) sets, so the ranking is correct. partition bycase将数据分为两个(更多)组,因此排序是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM