尝试在计算列的Case语句中使用Dense_Rank

时间:2016-05-15 14:36:49

标签: sql case dense-rank

为了提高我的SQL技能,我正在家里建立一个棒球统计数据库。我正在使用计算字段来获得击球平均值,我正在尝试在该场上使用dense_rank。我想排除任何少于150的球员,所以我把Dense_rank放在一个Case声明中。当我在Hits列上执行它而不是在Avg字段(这是一个计算字段)时,它工作。它不在Case语句中时(在查询中注释掉,粘贴在下面),但是当你把它放在Case语句中时,它会为所有内容返回相同的值。我已粘贴下面的整个查询,我在相关部分放了一个****,以便您可以找到它。有什么建议吗?

select 
    distinct b.playerid
    ,m.namelast +', '+ m.namefirst 'Player Name'
    ,case
        when t.name = 'Florida Marlins'
        then 'Miami Marlins'
        else t.name
        end Team
    ,case b.lgid
        when 'NL' then 'National'
        when 'AL' then 'American'
        else b.lgid 
        end League
    ,b.yearid Year
    ,case 
        when y.POS in ('LF','RF','CF') 
        then 'OF' 
        else y.pos end Position
    ,b.g G,b.AB
    ,b.h Hits
    ,dense_rank() over 
        (partition by t.name, b.yearid order by 
            case
                when b.ab>='150'
                then b.h
                end desc
                ) 'Hit Rank'
    ,cast(isnull(cast(b.h as numeric)/nullif(cast(b.ab as numeric),0),0) as decimal(10,3)) 'Avg.'
****    ,dense_rank() over 
        (partition by t.name, b.yearid order by
         --cast(isnull(cast(b.h as numeric)/nullif(cast(b.ab as numeric),0),0) as decimal(10,3)) desc
            case
                when b.ab>='150'
                then cast((isnull(cast(b.h as bigint)/nullif(cast(b.ab as bigint),0),0)*1000) as bigint)
                end desc
                ) 
                'AVG Rank'
    ,b.R,b.[2B],b.[3B] ,b.hr HR
    ,b.sb SB,b.cs CS,b.bb BB,b.so SO,b.ibb IBB,b.hbp HBP
from batting b
    join teams t on b.teamid=t.teamid and t.yearid=b.yearid and t.lgid=b.lgid
    join master m on b.playerid=m.playerid
    join fielding f on b.playerid=f.playerid and b.yearid=f.yearid and b.teamid=f.teamid and m.playerid=f.playerid and f.teamid=t.teamid
    join    
        (
        select f.playerid, f.yearid, f.teamid, f.pos, isnull(f.po,0) PO, isnull(f.a,0) A, isnull(f.e,0) E, isnull(f.dp,0) DP, isnull(f.g,0) G, isnull(f.innouts,0) innouts
        ,(isnull(f.po,0)+ isnull(f.a,0)+ isnull(f.e,0)+ isnull(f.dp,0)+ isnull(f.g,0)+ isnull(f.innouts,0)) Total
        from fielding f
            join    
                (
                select playerid, yearid, max(po) PO, max(g) G, isnull(max(innouts),0) innouts
                ,(isnull(po,0) + isnull(a,0) + isnull(e,0) + isnull(dp,0) + isnull(g,0) + isnull(innouts,0)) Total
                from fielding
                group by playerid, yearid, po, a, e, dp, g, innouts
                ) z on f.playerid=z.playerid and f.yearid=z.yearid
        group by f.playerid, f.yearid, f.stint, f.teamid, f.pos, f.po, f.a, f.e, f.dp, f.g, f.innouts
        having (isnull(f.po,0)+ isnull(f.a,0)+ isnull(f.e,0)+ isnull(f.dp,0)+ isnull(f.g,0)+ isnull(f.innouts,0))=max(z.total)
        ) y on f.playerid=y.playerid and f.yearid=y.yearid
where
    b.yearid='2015'
    and t.name='new york mets'
order by
    12,4,3,5,2

0 个答案:

没有答案