当前位置:数据库 > > 正文

sql两列数据快速对比(在sql中对两列数据进行运算作为新的列操作)

时间:2022-04-02 10:19:11类别:数据库

sql两列数据快速对比

在sql中对两列数据进行运算作为新的列操作

如下所示:

select a1,a2,a1+a2 a,a1*a2 b,a1*1.0/a2 c from bb_sb

把a表的a1,a2列相加作为新列a,把a1,a2相乘作为新列b,注意:

相除的时候得进行类型转换处理,否则结果为0.

select a.a1,b.b1,a.a1+b.b1 a from bb_sb a ,bb_cywzbrzb b

这是两个不同表之间的列进行运算。

补充知识:Sql语句实现不同记录同一属性列的差值计算

所使用的表的具体结构如下图所示

sql两列数据快速对比(在sql中对两列数据进行运算作为新的列操作)

Table中主键是(plateNumber+currentTime)

要实现的查询是:

给定车牌号和查询的时间区间,查询给定的时间区间内所包含记录的currentTime的差值,并计算AverageSpeed和该差值的乘积,求这段时间内的最高速度(HighestSpeed),并按照type值得不同进行划分。–>(type值只有0和1两个值)

主要思路是,首先能够得出的是相同type类型下同一个车牌号(也即同一车辆)在给定的时间区间内的currentTime的差值,比如按照currentTime排序号,相邻两条记录currentTime的差值,得出这个以后,其余的都可以通过聚合函数得出。

我们以车牌号为京A111111为例,设计如下图所示的测试用例。

sql两列数据快速对比(在sql中对两列数据进行运算作为新的列操作)

可以看到车牌号为京A111111的车辆总共有6条记录,其中type为0的有两条,type为1的有4条,

我们首先计算时间的差值,sql语句书写如下:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • SELECT a.platenumber,
  •   a.currenttime,
  •   a.type,
  •   a.averagespeed,
  •   a.highestspeed,
  •   currenttime - (SELECT currenttime
  •       FROM carmultispeedinfo
  •       WHERE platenumber = a.platenumber
  •         AND type = a.type
  •         AND currenttime < a.currenttime
  •       ORDER BY currenttime DESC
  •       LIMIT 1)AS timediff
  • FROM carmultispeedinfo a
  • 通过navicat可以看到如下图所示的查询结果:

    通过核查timediff的值是正确的,这样之后就可以在这个基础上添加内容了。

    完整的sql语句如下:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • SELECT Sum(aa.averagespeed * aa.timediff) AS milesdiff,
  •   Max(aa.highestspeed)    AS HighestSpeed,
  •   Sum(aa.timediff)     AS timediff,
  •   aa.type
  • FROM (SELECT a.platenumber,
  •     a.currenttime,
  •     a.type,
  •     a.averagespeed,
  •     a.highestspeed,
  •     currenttime - (SELECT currenttime
  •         FROM carmultispeedinfo
  •         WHERE platenumber = a.platenumber
  •           AND type = a.type
  •           AND currenttime < a.currenttime
  •         ORDER BY currenttime DESC
  •         LIMIT 1) AS timediff
  •   FROM carmultispeedinfo a)aa
  • WHERE aa.platenumber = '京A111111'
  •   AND aa.currenttime >= 1521790124670
  •   AND aa.currenttime <= 1521790125685
  • GROUP BY aa.type
  • 显示结果如下:

    sql两列数据快速对比(在sql中对两列数据进行运算作为新的列操作)

    经过核对,是我们想要得出的结果。之后将sql对应替换到mybatis的mapper文件中就可以了。<记录一下,备忘>将来有更深入的理解之后会继续更新,谢谢大家,希望能给大家一个参考,也希望大家多多支持开心学习网。

    原文链接:https://blog.csdn.net/u013703363/article/details/62893063

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐