为了提高我的 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