Partition By In SQL 中的条件语句
A conditional statement within a Partition By In SQL
我有一个具有 运行 宁计数 (timesRaced_byEvent) 的查询,以显示一匹马有多少次 运行 特定事件。我的问题是 TimesWon_byEvent,我希望该字段显示特定事件中一匹马获胜(排名第一)的次数 运行ning,但如您所见,我不太清楚那里....
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
如果我没理解错的话,你似乎想要:
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
等同于 "event"。但这应该可以满足您的要求。
我有一个具有 运行 宁计数 (timesRaced_byEvent) 的查询,以显示一匹马有多少次 运行 特定事件。我的问题是 TimesWon_byEvent,我希望该字段显示特定事件中一匹马获胜(排名第一)的次数 运行ning,但如您所见,我不太清楚那里....
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
如果我没理解错的话,你似乎想要:
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
等同于 "event"。但这应该可以满足您的要求。