sql - 当字段数大于前一天时返回记录

时间:2016-08-19 16:04:16

标签: sql-server-2008-r2

我正在使用sql server和一个包含以下数据的表(玩家)(08/05/2016是当前日期):

date         player  sport      games
08/05/2016   max     soccer     8
08/05/2016   steve   baseball   8
08/05/2016   max     football   6
08/05/2016   max     ping pong  5
08/04/2016   steve   baseball   4
08/04/2016   max     soccer     3
08/04/2016   max     football   8

我试图通过运动比前一天玩更多的游戏来获得结果。

当玩家为特定运动玩了比前一天更多的游戏时,我想创建带有日期,玩家,运动和more_games的输出,这样上面的查询结果将如下所示:

date         player  sport    more_games
08/05/2016   max     soccer       5
08/05/2016   steve   baseball     4 
08/05/2016   max     ping pong    5

**注意:没有显示游戏比前一天少,或者根本没有玩过的记录,但是在今天比赛时显示记录但不是昨天。

我有以下选择:

(---从当前日期获取记录---)

Select date, player, sport, games from players where date=getdate() 

(---从以前的日期获取记录---)

Select date, player, sport, games from players where date=dateadd(d, -1,getdate())

我只是不知道如何比较两个选择并放入最终结果集。我想到每个选择别名然后比较记录。可以使用一点帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

       select x.dateplay as [date], x.players,x.game as Sports, (x.score -isnull(y.score,0)) as more_games
       from
       (SELECT     dateplay, players, game, score,  convert(varchar,dateplay,101) as exp1
        FROM         dbo.players
        where convert(varchar,dateplay,101) = convert(varchar,getdate(),101)) x left outer join 
       (
       SELECT     dateplay, players, game, score, convert(varchar,dateplay,101) as exp1
       FROM         dbo.players
       where convert(varchar,dateplay,101) = convert(varchar,dateadd(day,-1,getdate()),101)
       ) y on x.players =y.players and x.game = y.game -- and  x.score > y.score
       where   (x.score- isnull(y.score, 0))>=0 

试试这段代码,它在SQL中运行良好

答案 1 :(得分:0)

所以根据你的说法,这给了我们所有球员以及他们按日期比赛的比赛次数。

Select base.date, base.player, base.sport, base.games 
from players base

现在我们加入到前一天(并检查游戏更大)

Select base.date, base.player, base.sport, base.games 
from players base
join players prior on base.player = prior.player 
                  and base.sport = prior.sport
                  and base.date = dateadd(day,1,prior.date)
where base.games > prior.games

如果您今天只想要,请添加

  and base.date = getdate()

注意我使用了sql server dateadd,因为你的平台上并不清楚你在你的例子中使用过它。在mysql中,您将使用DATE_ADD(prior.date,INTERVAL 1 DAY);