计算多个值的最大单个间隙

时间:2017-06-21 03:00:32

标签: mysql sql

我的表:

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

提前致谢。

2 个答案:

答案 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问题。 可能它可以帮助将来的某个人 你如何做到以下几点:

  1. 通过SQL
  2. 检索$ query_result
  3. 创建变量$ name =“”,$ year = 0,$ diff = -1
  4. 遍历每个$行并检查   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']
  5. 对于打印,您可以在$ row ['name']为!= $ name时打印以前的值 或者,以{key:value} JSON格式保存它们并最后打印!