Search code examples
sqlsql-serverwindow-functions

A conditional statement within a Partition By In SQL


I have a query that has a running count (timesRaced_byEvent) to show how many times a horse has run a particular event. My problem is the TimesWon_byEvent, where I want that field to show a running count of occasions where a horse won (placed 1st) for a particular event, but as you can see I'm not quite there.... 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

Solution

  • If I understand correctly, you seem to want:

    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;
    

    I'm a little confused by the column names. You seem to equate racelength with "event". But this should do what you are asking.