1

桌上联赛

team_id name        wins    losses  played  recorded    created
1       dodgers     10      4       14      1364790000  1353215830
2       angels      9       6       15      1364790000  1353661376
3       pirates     12      3       15      1364790000  1353543466

team_id name        wins    losses  played  recorded    created
1       dodgers     22      9       31      1367274480  1353215830
2       angels      14      17      31      1367274480  1353661376
3       pirates     19      13      32      1367274480  1353543466
4       yankees     10      9       19      1367274480  1365577298
5       brewers     7       11      18      1367274480  1365394448

希望结果为:

team_id name        wins    losses  played
1       dodgers     12      5       17      
2       angels      5       11      16
3       pirates     7       10      17
4       yankees     10      9       19
5       brewers     7       11      18

我已经尝试了几个使用连接的查询,但都没有成功。每天,球队的胜利、失败和比赛都会被记录下来,并在记录栏上加盖时间戳。团队是在 created 列上创建的。(所有unix时间戳)我正在尝试的两个日期之间有几行,但我不需要它们来进行此查询。

我想做的是为现有和新团队获得四月的赢/输/出场,我尝试了几个查询,这里有几个没有给我想要的结果:

SELECT a.name as name, a.wins-b.wins as wins, a.losses-b.losses as losses, a.played-b.played as played from league a join league b on a.id=b.id where a.recorded= 1367274480 and b.recorded= 1364790000

SELECT new.*, new.wins-old.wins as newwins, new.losses-old.losses as newlosses FROM league new LEFT JOIN league old ON new.id=old.id WHERE (new.recorded=1367274480 and old.recorded=1364790000) or (new.created > 1364790000 and new.recorded=1367274480) GROUP BY new.id
4

2 回答 2

0

您希望后面的记录的每一行和前面的记录的行数相同,因此您需要使用 LEFT JOIN 为在两个日期之间创建的团队获取 NULL,但WHERE recorded较小表的条件应作为ON连接条件移动。

还请记住2-NULL = NULL,因此您需要使用 coalesce() 将 NULL 更改为 0。

SELECT a.name AS name, 
       a.wins - COALESCE( b.wins, 0 ) AS wins, 
       a.losses - COALESCE( b.losses, 0 ) AS losses, 
       a.played - COALESCE( b.played, 0 ) AS played
FROM league a LEFT JOIN league b 
ON a.team_id = b.team_id AND b.recorded =1364790000
WHERE a.recorded =1367274480
于 2013-05-01T02:25:52.253 回答
0

数据设置的方式,好像你每天都没有记录值。但是,每一列都会增加,因此您可以计算该月的最大值和最小值之间的差异。

尝试这个:

SELECT l.name as name,
       max(l.wins)-min(l.wins) as wins,
       max(l.losses)-min(l.losses) as losses,
       max(l.played)-min(l.played) as played
from league l
where l.recorded <= 1367274480 and l.recorded >= 1364790000
group by l.name
于 2013-05-01T01:47:38.867 回答