我坚持根据特定条件对行进行分类的过程。我希望在你们的支持下完成这一切!
基本上,我试图通过应用一些特定的公式创建两个新列。这些列用于对每年的数量进行排名,也可以通过指定每个实践是否包含在top 3 claims
或2014
中的not
来进行分类。在下面的示例中,light blue
中突出显示的列是我要创建的列。
我的查询如下 - 现在我在为from
上方的最后两行编写代码时遇到问题,group by
和having
似乎在这些括号内不起作用。请帮忙!!
select
fiscal_year,
prac,
count(*) "CLAIMS",
sum(paid_amount) "COST",
row_number() over (group by fiscal_year order by count(*) desc) "Annual Rank by Claims",
case
when row_number() over (having fiscal_year = '2014' order by count(*) desc) < 4
then 'YES'
else 'NO'
end "PRAC TOP 3 IN CLAIMS 2014"
from mys.mv_claim
where category = 'V'
group by fiscal_year,
prac
/
答案 0 :(得分:0)
缺少原始数据,让给定(中间)输出作为起始点 - 第一个语句(导致 MV_Claim_Ranked )可以替换为 mys.mv_claim中的选择强>:
WITH
MV_Claim_Ranked AS (
SELECT
fiscal_year,
prac,
claims,
cost,
annual_rank_by_claim,
RANK() OVER (PARTITION BY fiscal_year ORDER BY claims DESC) annual_rank_by_claim_calc,
prac_top_3_in_claims_2014
FROM MV_Claim_Grouped
)
SELECT
T1.*,
CASE WHEN (SELECT annual_rank_by_claim_calc
FROM MV_Claim_Ranked T2
WHERE T1.prac = T2.prac
AND T2.fiscal_year = 2014) < 4
THEN 'YES' ELSE 'NO' END AS prac_top_3_in_claims_2014_calc
FROM MV_Claim_Ranked T1
ORDER BY prac, fiscal_year
;
您的汇总将被保留以供参考。
查看实际操作:SQL Fiddle。
如果需要调整/进一步详细说明,请发表评论。
答案 1 :(得分:0)
我从来没有见过GROUP BY和HAVING在分区规范中使用过;我怀疑这是一个语法错误。我认为您的查询需要看起来更像:
WITH t as (
select
fiscal_year,
prac,
count(*) "CLAIMS",
sum(paid_amount) "COST"
from mys.mv_claim
where category = 'V'
group by fiscal_year, prac
)
SELECT
t.*,
rank() over (partition by fiscal_year order by claims desc) "Annual Rank by Claims",
case
when prac in(select prac from (select * from t where fiscal_year = 2014 order by claims desc ) where rownum <= 3)
then 'YES'
else 'NO'
end "PRAC TOP 3 IN CLAIMS 2014"
from t
我使用了排名而不是行号,因为两个相同的声明计数会产生相同的排名值。排名将跳过下一个排名(两个999索赔计数将每个排名1,一个998索赔计数将排名3.如果您希望它排名2使用dense_rank)
如果你对此有任何错误,请告诉我,因为我唯一不确定的事情是找回前3个实践的子选择。这可以通过左连接来完成(我更有信心)