我希望在我的代码中,从数据库当前月份读取数据应该在上个月的24日到本月23日之间。换句话说,日历月份在24到23之间。
我正在使用以下代码。
月和年计算
<cfset curmonth=Month(now())>
<cfif #curmonth# eq 1>
<cfset prevmonth=12>
<cfelse>
<cfset prevmonth=#curmonth# - 1>
</cfif>
<cfset curyear=Year(now())>
<cfset prevyear=#curyear# - 1>
这是查询:
<cfquery name="GetMonthlySpentbudget" datasource="#Application.ds#" dbtype="ODBC">
SELECT
IF(SUM(amount) IS NULL,0,SUM(amount)) as monthlyspentbudget
FROM orders o
WHERE
<cfif #curmonth# neq 1>
if(IsOverBudget=1,
DATE(ApprovedDate1)>='#curyear#-#prevmonth#-24' AND
DATE(ApprovedDate1)<='#curyear#-#curmonth#-23',
DATE(ApprovedDate)>='#curyear#-#prevmonth#-24' AND
DATE(ApprovedDate)<='#curyear#-#curmonth#-23'
)
<cfelse>
if(IsOverBudget=1,
DATE(ApprovedDate1)>='#prevyear#-#prevmonth#-24' AND
DATE(ApprovedDate1)<='#curyear#-#curmonth#-23',
DATE(ApprovedDate)>='#prevyear#-#prevmonth#-24' AND
DATE(ApprovedDate)<='#curyear#-#curmonth#-23'
)
</cfif>
AND
FacilityID= #FacilityID#
AND
o.ApprovedFlag = 1
AND
o.ApprovedFlag1 = 1
</cfquery>
现在我想在另一个查询中完全按月计算。这是查询:
SELECT
MONTHNAME(approveddate1) AS sMonth,
YEAR(approveddate1) AS iYear,
SUM(o.amount) AS TotalSale,FacilityId
FROM orders AS o
WHERE
o.ApprovedFlag = 1
AND
o.ApprovedFlag1 = 1
GROUP BY FacilityId, MONTH(approveddate1)
Order by FacilityId, iyear, smonth
如何修改查询以使月份在24到23之间?
答案 0 :(得分:3)
也许是这样的:
SELECT
MONTHNAME(GroupingDate) AS sMonth,
YEAR(GroupingDate) AS iYear,
SUM(amount) AS TotalSale,
FacilityId
FROM (
SELECT
FacilityId,
amount,
DATE_ADD(
approveddate1,
INTERVAL IF(DAY(approveddate1) < 24, 0, 1) MONTH
) AS GroupingDate
FROM orders
) AS o
GROUP BY
YEAR(GroupingDate),
MONTH(GroupingDate),
MONTHNAME(GroupingDate),
FacilityId