建立过去12个月的月度总数

时间:2009-03-06 15:10:59

标签: sql database datetime vb6 date

CurrentMonth = Month(CurrentDate)
CurrentYear = Year(CurrentDate)

    SQL = "SELECT Spent, MONTH(Date) AS InvMonth, YEAR(Date) As InvYear FROM Invoices WHERE YEAR(Date) = '" & CurrentYear & "' AND MONTH(Date) = '" & CurrentMonth & "'"
    RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
    Do Until RecordSet.EOF
        MTotal(i) = MTotal(i) + RecordSet.Fields("Spent")
        RecordSet.MoveNext
    Loop
    RecordSet.Close

这是我目前在一个月内累计花费的代码。 我希望在过去的12个月内将其扩展为每月检索总数。

我看到这样做的方法是向后循环通过CurrentMonth值,如果CurrentMonth值达到0,则将CurrentYear的值回滚1.使用循环变量(i)构建一个包含12个值的数组: MTotal()

你们有什么想法?

4 个答案:

答案 0 :(得分:1)

小组应该让你在路上。

SELECT TOP 12
  SUM(Spent) AS Spent
  , MONTH(Date) AS InvMonth
  , YEAR(Date) AS InvYear
FROM
  Invoices
GROUP BY
  YEAR(Date), MONTH(Date)
WHERE DATEDIFF(mm, Date, GETDATE(()) < 12

Josh的DATEDIFF是比原版TOP和ORDER BY更好的解决方案

答案 1 :(得分:1)

我会通过将日期“舍入”到月份来解决这个问题,然后按月份日期进行分组,并总计花费的金额:

 SELECT SUM(Spent) AS [TotalSpent],
        DATEADD(Month, DATEDIFF(Month, 0, [Date]), 0) AS [MonthDate]
 FROM   Invoices 
 WHERE      [Date] >= '20080301'
        AND [Date] <  '20090301'
 GROUP BY DATEADD(Month, DATEDIFF(Month, 0, [Date]), 0)
 ORDER BY [MonthDate]

可以将[MonthDate]格式化为适当地显示月份/日期,或者在单独的列中显示。

可以对WHERE子句进行参数化,以提供适当的记录范围

答案 2 :(得分:0)

唯一的问题是,我需要每月总计,过去12个月中的每一个月,而不是过去12个月的总数。否则我看到如何改进SQL而不是使用vb6代码oculd是一个更好的选择。

答案 3 :(得分:0)

我想出的解决方案是:

For i = 0 To 11
    If CurrentMonth = 0 Then
        CurrentMonth = 12
        CurrentYear = CurrentYear - 1
    End If

    SQL = "SELECT Spent, MONTH(Date) AS InvMonth, YEAR(Date) As InvYear FROM Invoices WHERE YEAR(Date) = '" & CurrentYear & "' AND MONTH(Date) = '" & CurrentMonth & "'"
    RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
    Do Until RecordSet.EOF
        MTotal(i) = MTotal(i) + RecordSet.Fields("Spent").Value
        RecordSet.MoveNext
    Loop
    RecordSet.Close

    CurrentMonth = CurrentMonth - 1
Next

我相信这应该按预期工作。但是我仍然期待看到你们可以提出什么解决方案,或者是否有人发现ym修复问题。