首页 > 解决方案 > 在添加新数据之前删除上个月

问题描述

我正在 SpotFire 中设置一个新的数据表。由于最新更新 SpotFire X,我们可以使用自动化服务作业生成器。因此,我想创建作业计划,它将自动将(新)数据附加到我现有的数据表中。我对脚本和编程很陌生,所以任何帮助都将不胜感激。我有一个与我的 Spotfire 仪表板连接的 SAP BW 查询。此查询仅包含最近一个月的数据。由于自动化服务作业生成器只有每周间隔,我想在让调度程序添加数据之前实现一些智能。查询不会每周/每天刷新,而是每月刷新。这就是为什么我希望脚本在将数据附加到数据表之前先删除(如果可能的话)数据,否则我会在数据表中得到重复项。

我试图搜索脚本,但找不到任何有用的东西。我确实找到了这个脚本。

dtTarget=usertable*
selection = IndexSet(dtTarget.RowCount,True)
for r in selection:
selection[r] = (r>=(dtTarget.RowCount-10))
dtTarget.RemoveRows(RowSelection(selection))

标签: pythondatabasescriptingspotfire

解决方案


对于下面的示例代码,我使用了具有以下内容的 Spotfire 文件:

Spotfire 数据表名称 = Store

保存日期的数据列名称 = [日期]

数据是从 Spotfire 演示数据数据库加载的。

如果你只是想在加载前清空表格,你可以使用这个。

from Spotfire.Dxp.Data import RowSelection, IndexSet    
table = Document.Data.Tables["Store"]
table.RemoveRows(RowSelection(IndexSet(table.RowCount, True)))

如果您想删除比上个月更早的所有内容,但保留更新的所有内容,则可以这样做。将 None 传递给 last_month 函数将导致它从今天开始获取上个月。

from datetime import date, timedelta
from Spotfire.Dxp.Data import RowSelection

def last_month(from_date):
    if from_date is None:
        from_date = date.today()
    end_date = from_date.replace(day=1) - timedelta(days=1)
    start_date = date(end_date.year, end_date.month, 1)
    return (start_date, end_date)

table = Document.Data.Tables["Store"]
(start,end) = last_month(date(1994,12,6))
rows_to_delete = table.Select("[Date] <= Date('{}')".format(end.strftime("%x")))
table.RemoveRows(rows_to_delete)

您可以将实际表设置为 ironpython 脚本的输入参数,而不是像我所做的那样直接在脚本中命名它。您可以对日期列名称执行相同操作。


推荐阅读