Python on Sqlite db 中的行排序和选择逻辑

Row sorting and selection logic in Python on Sqlite db

您好,感谢您抽出宝贵时间回答我的问题。我在一个小城市的预算 space 工作,在这些不稳定的时间里,我正在学习一些 python 可能在将来帮助我进行一些财务数据建模。我们目前使用 SAP,但我也想学习一门新语言。

我需要一些关于在哪里寻找某些答案的指示。 例如,我创建了一个包含几百万条记录的数据库,按日期和时间排序。我能够剥离不需要的数据,现在有一个干净的数据库可以使用

在高层次上,我想知道如果根据一天中的第一条记录,同一天是否有另一个条目是第一条记录的两倍。

Date|time|dept|Value1
01/01/2019|11:00|BUD|51.00
01/01/2019|11:30|CSD|101.00
01/01/2019|11:50|BUD|102.00
01/02/2019|10:00|BUD|200.00
01/02/2019|10:31|BUD|201.00
01/02/2019|11:51|POL|400.00
01/03/2019|11:00|BUD|100.00
01/03/2019|11:30|PWD|101.00
01/03/2019|11:50|BUD|110.00

根据上面的数据和需求,我想得到

的输出
Date|time|dept|Value| Start Value
01/01/2019|11:50|BUD|102.00|51.00
01/02/2019|11:51|POL|400.00|200.00
01/03/2019|NONE|NONE|NONE|100.00

在第 3 天,没有任何值至少翻倍,因此我们有 none 或 null。

到目前为止我做了什么

我已经能够连接到数据库 [python] 2.我能够从数据库中删除不必要的信息和部门[sqlite] 3. 我已经能够为结果 [Python]

创建新的 tables

问题/最佳实践

  1. 如何获得每天的第一行。我是否从分配给 2019 年 1 月 1 日的循环之前的变量开始,然后选择行号并将其存储在另一个 table 中,或者我们在这里还有什么其他选项。
  2. 一旦每天的第一行是另一个 table 或数组中的 stored/captured,我如何获得至少两次出现在第一行的值的第一次出现。

例如?开始元代码************

Start from Line 1 to end
table2.date[] Should be equal to 01/01/2019
table2.value[] Should be equal to 51.00
look through each line if date = table2.date and value >= 2* (table2.value[])
*if successful, get record line number and department and value and store in new table
else
goto next line

Then increase table2.date and table2.value by 1 and do the loop again. 

结束元代码******************

这是正确的方法吗,我觉得为每个日期更改浏览数百万条记录并不是很优化。

如果日期不等于 table2.date[1],我可能会添加一个条件退出,但我仍然不确定这是否是解决此问题的正确方法。这将 运行 每年只有一两次,因此系统性能并不是那么重要,但我仍在考虑以正确的方式处理它。

  1. 我应该将最终数据导出到 excel 进行分析,还是 Python 中有很好的分析建模工具?专业人士会推荐什么?

你可以那样做,但你是对的,这需要很长时间。我不知道 SQLite 是否有能力有效地做你想做的事,但我知道 Python 有。听起来您可能想要使用 Python 数据分析库,Pandas。您可以在此处了解如何让您的 SQLite 进入 Pandas:

一旦你在 Pandas Dataframe 中拥有它,就有大量的函数可以获取某些东西的第一次出现,找到重复项,找到唯一值,甚至生成其他只有唯一值的数据框。

您可以使用 exists 检查同一天是否存在另一条记录并且其值大于两倍,并且 window 函数用于过滤每天的最前面的记录:

select *
from (
    select 
        t.*,
        row_number() over(partition by date order by time) rn
    from mytable t
    where exists (
        select 1 from mytable t1 where t1.date = t.date and t1.value = 2 * t.value
    )
) t
where rn = 1

row_number() 不可用的 SQLite 版本中,另一个选项是使用相关子查询进行过滤:

select t.*
from mytable t
where 
    exists(select 1 from mytable t1 where t1.date = t.date and t1.value = 2 * t.value)
    and t.time = (select min(t1.time) from mytable t1 where t1.date = t.date)