Create a monthly amount for the last 12 months

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

This is the code that I currently have to add to the total spent for this month. I want to expand this to get monthly totals for the past 12 months.

The way I do this will be to scroll backward through the CurrentMonth value, and if the CurrentMonth value reaches 0 roll, the CurrentYear value backward 1. Using the loop variable (i) to create an array of 12 values: MTotal ()

What do you guys think?

+3
source share
4 answers

The group should help you with this.

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 is a better solution than my original TOP and ORDER BY

+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 ,

+1

, 12 , 12 . , SQL, vb6- oculd.

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.

0

Source: https://habr.com/ru/post/1704338/


All Articles