我试图对前8个月的前6个月的油价进行求和。我对如何将Sum和Rank函数合并到SQL代码中对此一无所知。
这是我的SQL代码:-
SELECT WELL_NAME,
Number_of_Months_on_Prod,
OIL,
ROW_NUMBER() OVER(PARTITION BY WELL_NAME ORDER BY OIL DESC) AS RANK_OIL,
SUM(CASE WHEN (RANK_OIL >= 1) AND (RANK_OIL) <= 6 THEN Coalesce(BOE6, 0) ELSE 0 END) Over (PARTITION BY WELL_NAME ) as BEST_6_OF_8_MONTH_OIL
FROM TABLE_WELL
ORDER BY WELL_NAME ;
我得到排序分析函数不能嵌套的错误。任何帮助将不胜感激。这是我的样本数据集。
答案 0 :(得分:1)
我看到了多个级别的窗口功能:
SELECT WELL_NAME, Number_of_Months_on_Prod, OIL,
SUM(CASE WHEN RANK_OIL <= 6 AND SEQNUM <= 8 THEN BOE6 END) OVER (PARTITION BY WELL_NAME) AS BEST_6_OF_8_MONTH_OIL
FROM (SELECT TW.*,
ROW_NUMBER() OVER (PARTITION BY WELL_NAME, (CASE WHEN SEQNUM <= 8 THEN 1 ELSE 2 END)
ORDER BY OIL DESC
) AS RANK_OIL
FROM (SELECT TW.*,
ROW_NUMBER() OVER (PARTITION BY WELL_NAME ORDER BY OIL DESC) AS SEQNUM
FROM TABLE_WELL TW
) TW
) TW
ORDER BY WELL_NAME ;