sql—在将csv读入spring启动应用程序时,如何将数据表列从累积转换为差异?

uidvcgyl  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(210)

我在一个表格里有数据,比如

date  | city | Cumulative total 
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    15
1/3/2020 | NYC  |    31
1/4/2020 | NYC  |    36
1/5/2020 | NYC  |    55
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    5
1/3/2020 | BER  |    13
1/4/2020 | BER  |    42
1/5/2020 | BER  |    45
 .
 .  // more data for BER continued
 .

我不想让这些数据 cumulative ,而是 difference . 基本上我想从前一天减去第二天,确保城市匹配。

date  | city | Cumulative total 
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    5
1/3/2020 | NYC  |    16
1/4/2020 | NYC  |    5
1/5/2020 | NYC  |    19
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    4
1/3/2020 | BER  |    8
1/4/2020 | BER  |    29
1/5/2020 | BER  |    3
 .
 .  // more data for BER continued
 .

我有一个csv中的数据,并将其加载到一个spring启动应用程序的数据库中。但是,spring启动应用程序需要的是差异,而不是累积。我怎样才能正确地转换这些数据呢
在从csv读取数据时在数据库中?
通过在 JpaRepository 所以我的pojo作为转换后的数据回来了?
我不知道如何实现前两个,但他们是我的想法做什么。我请求有人帮助我了解处理这种情况的最“行业标准”的方法是什么。也许有比我提议的更好的方法。
谢谢!

sf6xfgos

sf6xfgos1#

如果您的数据库支持窗口函数,那么这对于 lag() ,它允许您在给定 partition 以及 order by 规范:

select 
    t.*,
    cumulative 
        - lag(cumulative, 1, 0) over(partition by city order by date) as difference
from mytable t

并不是所有的数据库都支持 lag() ,在这种情况下,您可以:

select
    t.*,
    coalesce(
        cumulative - lag(cumulative) over(partition by city order by date),
        cumulative
    ) difference
from mytable t

相关问题