我有一个桌面游戏日,其中包含以下列:date_played,winner,loser 具有以下值,
(Jun-03-14, USA, China)
(Jun-05-14, USA, Russia)
(Jun-06-14, France, Germany)
.
.
.
.
(Jun-09-14, USA, Russia)
我需要获得美国在序列中正好赢得3行的所有实例。
我尝试了以下查询。
Select
date, winner, loser,
RANK() OVER (PARTITION BY winner ORDER BY date rows 2 preceding) as rank
from playday;
答案 0 :(得分:1)
首先你需要找出他们最后一次失败的时间。 第二个计算胜利的数量,大于(>)他们最后一次丢失的日期。 第三个返回大于最后一次丢失的所有行,如果count> 3。
抱歉,我前面没有SQL解析器,无法正确地将其放入代码中。Set @team_name = "USA";
select date, winner, loser
from playday
where (select count(*) as wins_since_loss from playday
where playday.winner = @team_name
and playday.date >
(select max(date) as losing_date from playday where playday.loser = @team_name)) = 3
答案 1 :(得分:1)
您可以使用以下查询。
select winner,loser,date,cnt from (select winner, loser, date, date - lag(date,3) over ( order by date) as cnt from playday) where cnt >=3
答案 2 :(得分:-1)
查询是拉美国连续三次获胜的行序列,不少于或少于(我使用日期作为date1)
select date1, winner, loser from
(
select count (*) over (partition by change) as id, date1,winner,loser from
(
select date1,winner,loser,lag_loser, sum(case when loser <> lag_loser and (loser='USA' or lag_loser='USA') then 1 else 0 end) over (order by date1 rows unbounded preceding) as change from
(
select date1, winner,loser, lag(loser) over (order by date1) as lag_loser from
(
select date1, winner, loser from playday
where winner ='USA' or loser = 'USA'
ORDER BY date1 ASC
)
)
)
)
where winner ='USA' and id =3