如何计算SQL中两行之间的差异?

时间:2014-03-11 18:04:23

标签: sql sqlplus multiple-columns difference

我的表是:

Bowlers:BName - Handed - 电话

表演:BName - TName - 得分

锦标赛:TName - TDate

我正在试图弄清楚如何计算名为弗雷德的投球手的得分差异。到目前为止我的代码是:

select tname, tdate, score
from tournaments
natural inner join 
performances
where bname = 'Fred'
order by tdate;

这给了我一张这样的表格:

 TName                    TDate                Score
 ------------------------ ------------ -------------
 Tournament 1             1/1/2014               250
 Tournament 2             1/8/2014               245
 Tournament 3             2/10/2014              215

现在我只需添加第四列,计算他在上一场锦标赛中得分的差异。所以完成的表看起来像这样:

 TName                    TDate                Score     Score_Dif
 ------------------------ ------------ ------------- -------------
 Tournament 1             1/1/2014               250             0
 Tournament 2             1/8/2014               245            -5
 Tournament 3             2/10/2014              215           -30

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

SQLPlus通常附加到Oracle,后者支持lag()函数。所以,你可以很容易地做你想做的事情:

select tname, tdate, score,
       coalesce(score - lag(score) over (order by tdate), 0) as diff
from tournaments natural inner join 
     performances
where bname = 'Fred'
order by tdate;

答案 1 :(得分:0)

假设您正在使用MySQL:

您可以使用临时变量来保存先前的值,然后您可以计算差异。看看this question and its accepted answer

出于特定目的,我会创建一个临时表来保存数据,然后我会查询该临时表并计算差异:

drop table if exists temp_data;
create temporary table temp_data
    select 
        tname, tdate, score
    from 
        tournaments
        natural inner join performances
    where 
        bname = 'Fred';
alter table temp_data
    add index idx_tname(tname),
    add index idx_tdate(tdate);
select tname, tdate, score, score_dif
from
    (
        select 
            tname, tdate, 
            @prevScore as previousScore, 
            a.score - @prevScore as score_dif, 
            @prevScore := a.score as score
        from
            (
                select @prevScore := 0
            ) as init,
            temp_data as a
        order by a.tdate
    ) as calcQuery;

希望这有帮助。