【问题标题】:A conditional statement within a Partition By In SQLPartition By In SQL 中的条件语句
【发布时间】:2018-08-21 17:50:48
【问题描述】:

我有一个查询,它有一个运行计数 (timesRaced_byEvent) 来显示一匹马运行了多少次特定事件。我的问题是 TimesWon_byEvent,我希望该字段显示在特定事件中一匹马获胜(排名第一)的情况的连续计数,但正如您所见,我并不完全在那里......

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

【问题讨论】:

  • 事件是否仅由马名和长度定义?这似乎不对。
  • 不,它们也由 UR_RDIndex 定义 - 这是关于马何时奔跑的索引,即 1 是马最近一次奔跑的时间,2 是上一次,等等等等
  • edit 你的问题。 解释您的数据及其含义。不要指望人们仅仅从样本数据和一个显然没有做你想让它做的事情的查询来判断你的意思(如果它做了,你就不会问问题)

标签: sql sql-server window-functions


【解决方案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 等同于“事件”。但这应该可以满足您的要求。

【讨论】:

  • 完美,我现在知道如何在分区中使用条件......只需将您的逻辑转换到我的表中......总和(当 ur_position = '1' then 1 else 0 end)结束(按#temp2.​​Horse、#temp2.​​UR_RaceLength 顺序按#temp2.​​Horse、#temp2.​​UR_RaceLength、#temp2.​​UR_RDIndex desc 划分)谢谢
猜你喜欢
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2021-11-14
  • 2015-11-29
相关资源
最近更新 更多