我在 SPSS Modeler 中有一个节点,其中包含下面提供的 SQL 代码。 它选择一个月并计算一个月的计数。 我创建了一个参数“$P-p_ly_parameter”并为其分配了值 201807。
我想做的是循环运行从 201807 到 201907 的月份。
我使用 Python 代码将其放入“工具”、“流属性”、“执行”中。
但是当我运行时它不会让我得到我期望的结果。 事实上我没有得到任何结果。
显然,我错过了一些东西。 我想循环的结果没有分配给每个月的month_id。
您能帮助我以正确的方式进行循环吗? 我应该使用选择节点并包含类似的内容吗?
-- SQL
SELECT
cust.month_id,
count(*) as AB_P1_TOTAL
FROM tab1 cust
JOIN tab2 dcust ON dcust.month_id=cust.month_id and
dcust.cust_srcid=cust.cust_srcid
WHERE
cust.month_id ='$P-p_ly_parameter'
group by cust.month_id
order by cust.month_id
# Python
import modeler.api
# boilerplate definitions
stream = modeler.script.stream()
taskrunner = modeler.script.session().getTaskRunner()
# variables for starting year
startYear = 2018
# gets us to 2019
yearsToLoop = 1
# get the required node by Id
# double click on node, go to annotations and get ID from bottom right
selectNode = stream.findByID('id5NBVZYS3XT2')
runNode = stream.findByID('id3N3V6JXBQU2')
# loop through our years
for year in range(0, yearsToLoop):
# loop through months
for month in range(1,13):
#month_id = str(startYear + year) + str(month).rjust(2,'0')#ar
p_ly_parameter = str(startYear + year) + str(month).rjust(2,'0')#ar
#debug
#print month_id
print p_ly_parameter
# set the condition in the select node
#selectNode.setPropertyValue('condition', 'month_id = ' + month_id)
#selectNode.setPropertyValue("condition", "'month_id = '$P-p_ly_parameter'")
#selectNode.setPropertyValue('mode', 'Include')
# run the stream
runNode.run(None)
我期望按月显示结果,例如 201807 500、201808 1000 等。 但现在我什么也没得到
缺少的部分是设置流参数的值。 这行代码表示:
p_ly_parameter = str(startYear + year) + str(month).rjust(2,'0')
仅设置Python脚本本身中变量的值,但不会更改同名流参数的值。
您需要紧随其后添加一行,明确设置 stream 参数的值,例如:
stream.setParameterValue("p_ly_parameter", p_ly_parameter)
或者定义一个流参数,即 SNAPSHOT_MONTH ,在 SQL 语句中使用它,即 WHERE TO_DATE(cust.month_id) >= '$p_ly_parameter' 和 TO_DATE(cust.month_id) < add_months('$p_ly_parameter',+1) , enter the below Python code in the modeler Execution Python editor , and run:
import modeler.api
from datetime import date, timedelta, datetime
from calendar import mdays
#Set Date
first_date = datetime(2018 , 7 , 1)
last_date = datetime(2019 , 7 , 1)
# boilerplate definitions
stream = modeler.script.stream()
taskrunner = modeler.script.session().getTaskRunner()
datelist = [first_date.strftime('%Y-%m-%d')]
while first_date < last_date:
first_date += timedelta(days=32)
first_date = first_date.replace(day=1)
datelist.append(datetime(first_date.year, first_date.month, 1).strftime('%Y-%m-%d'))
i=0
for date in datelist:
i+=1
print(i)
Q_Date = date
print(Q_Date)
stream.setParameterValue("p_ly_parameter", Q_Date)
modeler.script.stream().findByID("id6IRXA9LJR1S").run(None)
确保您在最后一行输入的 ID 代表您的 stram 终端节点的 ID(即导出节点)