我正在尝试计算来自数据库的值列表的差异。 我想用php或mysql实现它,但我不知道如何继续。 我有一个名为player_scores的表。其中一行包含得分的目标。
实施例
pl_date pl_scores
03/11/2014 18
02/11/2014 15
01/11/2014 10
我想回应一下在不同日期比赛中进球的差异。
Ex:
pl_date pl_scores diff
03/11/2014 18 +3
02/11/2014 15 +5
01/11/2014 10 no diff
如何获得所需的结果?
答案 0 :(得分:1)
您似乎想要将分数与前一行的分数进行比较。
如果使用获得最大pl_date且小于当前行的pl_date的子查询完成,则可能最简单,然后将该子查询的结果反馈到player_scores表以获取每个日期的详细信息: - < / p>
SELECT ps1.pl_date, ps1.pl_scores, IF(ps2.pl_date IS NULL OR ps1.pl_scores = ps1.pl_scores, 'no diff', ps1.pl_scores - ps1.pl_scores) AS diff
FROM
(
SELECT ps1.pl_date, MAX(ps2.pl_date) prev_date
FROM player_scores ps1
LEFT OUTER JOIN player_scores ps2
ON ps1.pl_date > ps2.pl_date
GROUP BY ps1.pl_date
) sub0
INNER JOIN player_scores ps1
ON sub0.pl_date = ps1.pl_date
LEFT OUTER JOIN player_scores ps2
ON sub0.prev_date = ps2.pl_date
还有其他方法可以做到这一点(例如,使用变量来处理有序子查询的结果,将每一行与存储在前一行变量中的值进行比较)
答案 1 :(得分:0)
select *,
coalesce(
(SELECT concat(IF(t1.pl_scores>t2.pl_scores,'+',''),(t1.pl_scores-t2.pl_scores))
FROM tableX t2 WHERE t2.pl_date<t1.pl_date ORDER BY t2.pl_date DESC LIMIT 1)
, 'no data' ) as diff
FROM tableX t1
WHERE 1
order by t1.pl_date DESC
答案 2 :(得分:0)
您可以使用两个查询,一个用于获取要在比较中使用的值(在下面的示例中是较小的分数),第二个用于获取具有差异的专用列的记录:
SELECT MIN(pl_scores);
SELECT pl_date, pl_scores, (pl_scores - minScore) as diff FROM player_scores;
或者,使用事务(一个查询执行php端):
START TRANSACTION;
SELECT MIN(Importo) FROM Transazione INTO @min;
SELECT Importo, (Importo - @min) as diff FROM Transazione;
答案 3 :(得分:0)
SELECT score FROM TABLE WHERE DATE = TheDateYouWant
$score = $data['score'];
SELECT score FROM TABLE WHERE date = dateYouWant
$difference = $score - $data['score'];
这样的东西?