我的表:
id name year
1 Carl 1923
2 Carl 1924
3 Carl 1927
4 Carl 1939
5 Carl 1990
6 Carl 1992
7 Carl 1993
8 Suki 1962
9 Suki 1972
10 Suki 2002
11 Suki 2003
我想计算卡尔和苏基之间最大差距。所以我期待的结果是:
Carl 51
Suki 30
提前致谢。
答案 0 :(得分:1)
您真的需要lag()
或lead()
功能。如果没有,一种方法是相关的子查询:
select name, max(year - prev_year) as max_diff
from (select t.*,
(select t2.year
from t t2
where t2.name = t.name and t2.year < t.year
order by year desc
limit 1
) as prev_year
from t
) t
group by name;
如果您知道id
没有间隙(至少在名称中),则可以使用性能更高的join
查询:
select t.name, max(t.year - tprev.year) as max_diff
from t join
t tprev
on t.year = tprev.year + 1 and t.name = tprev.name
group by t.name;
答案 1 :(得分:-1)
抱歉,我后来才意识到这不是一个PHP问题。 可能它可以帮助将来的某个人 你如何做到以下几点:
if $row['name'] is != $name
if so then do $year=$row['year'] and $diff=0,
else check if($diff<($row['year']-($year+$diff)))
#update diff
$diff=$row['year']-($year+$diff)
$year=$row['year']