我有一个场景,我将一个任务的“上次完成日期”记录为我的数据库中的列,以及另一列中下一个计划任务的间隔时间段(以天为单位)。我想将该日期添加到维护期间,如果它大于#now()#,请勾选一个计数器,以便我可以为所有记录计算。
这是我尝试的方式,但我对逻辑感到困惑。我的值总是为零所以我显然做错了。数字应该是17,因为我通过手工操作我的数据库记录手动计算它。
<!--- Get list of all active equipment--->
<cfquery name="get_equipment_tally" datasource="#datasource#">
select *
from equipment_maintenance
where active = 'yes'
ORDER by customer_name
</cfquery>
<cfset counter = 0>
<cfloop query="get_equipment_tally">
<!--- Set the due date for service = the particular maintenance interval added to the last service date. --->
<cfset dueDateTally = dateAdd("d", maintenance_interval , Date_last_completed) />
<!--- Get list of all active equipment that needs maintenance today--->
<cfquery name="get_equipment_attention_tally" datasource="#datasource#">
select *
from equipment_maintenance
where active = 'yes' AND #dueDateTally# <= #now()#
ORDER by customer_name
</cfquery>
<cfset counterNew = #counter# + #get_equipment_attention_tally.recordcount#>
</cfloop>
<cfoutput>#counterNew#</cfoutput>
答案 0 :(得分:1)
如果您只想计算now()之前的维护日期数和现在()之后的数字,那么代码逻辑可以更加简单。类似的东西:
<!--- Get list of all active equipment--->
<cfquery name="get_equipment_tally" datasource="#datasource#">
select *
from equipment_maintenance
where active = 'yes'
ORDER by customer_name
</cfquery>
<cfset counter_after_today = 0>
<cfset counter_today_or_before = 0>
<cfloop query="get_equipment_tally">
<!--- Set the due date for service = the particular maintenance interval added to the last service date. --->
<cfset dueDateTally = dateAdd("d", maintenance_interval , Date_last_completed) />
<cfif dueDateTally LTE now()>
<cfset counter_today_or_before = counter_today_or_before + 1>
<cfelse>
<cfset counter_after_today = counter_after_today + 1>
</cfif>
</cfloop>
<cfoutput>
counter_today_or_before: #counter_today_or_before# <br>
counter_after_today: #counter_after_today#
</cfoutput>
答案 1 :(得分:0)
您应该可以使用一个查询执行此操作。像这样:
<cfquery name="theQuery">
select field1, field2
, case when your date logic is one thing then 1 else 0 end dateLogic
from etc
<cfquery>
<cfset yourNumber = arraySum(theQuery['dateLogic'])>
您可以计算出实际细节。
修改强>
您的实际案例逻辑可能是这样的:
, case when dateadd(day, maintenanceInterval, date_last_completed) <= getDate() then 1
else 0 end isOverDue
请注意,我不使用MySQL,因此我使用的是MSSql语法。
答案 2 :(得分:0)
你可能会过于复杂化。如果目标只是计算今天或将来的任何时间安排维护的设备数量,则根本不需要循环。它可以通过单个查询完成。只需应用适当的日期过滤器和COUNT(*)
记录:
<cfquery name="get_equipment_tally" ...>
SELECT COUNT(*) AS TotalItems
FROM equipment_maintenance
WHERE DATE_ADD(Date_last_completed, INTERVAL maintenance_interval DAY)
>= <cfqueryparam value="#now()#" cfsqltype="cf_sql_date">
</cfquery>
<cfoutput>Total Items: #get_equipment_tally.totalItems# </cfoutput>
NB:如果需要,请调整cfsqltype。类型cf_sql_date
包括当前日期仅 .Type cf_sql_timestamp
包括当前日期和时间。