在SQL中Partition By中的条件语句

时间:2018-08-21 17:50:48

标签: sql sql-server window-functions

我有一个查询,该查询的运行计数(timesRaced_byEvent)显示一匹马运行特定事件的次数。我的问题是TimesWon_byEvent,在这里我希望该字段显示特定事件中一匹马获胜(排名第一)的情况的连续计数,但是如您所见,我还不在那里。 enter image description here

select #temp2.Horse
    , #temp2.RaceLength
    , #temp2.Position
    , #temp2.RDIndex
    , count(#temp2.RaceLength) over (Partition by #temp2.Horse, #temp2.RaceLength order by #temp2.Horse, #temp2.RaceLength, #temp2.RDIndex desc) - 1 as TimesRaced_byEvent
    , TimesWon_ByEvent
from #temp2 
Left join 
(
    Select Horse
        , RDIndex
        , RaceLength
        , count(RaceLength) over (Partition by Horse, RaceLength order by Horse, RaceLength,RDIndex desc) - 1 as TimesWon_ByEvent
    from #temp2
    where Position = '1'
) win on #temp2.Horse = Win.Horse 
    and #temp2.RDIndex = Win.RDIndex 
    and #temp2.RaceLength = Win.RaceLength
order by #temp2.RDIndex

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您似乎想要:

select t.*,
       (row_number() over (partition by horse, racelength order by rdindex desc) - 1) as timesRacedbyEvent,
       sum(case when ur_position = 1 then 1 else 0 end) over (partition by order, racelength order by rdindex desc) as 
from #temp2 t;

我对列名有些困惑。您似乎将racelength等同于“事件”。但这应该可以满足您的要求。