Aggregate SQL query grouping by month

前端 未结 5 1735
忘掉有多难
忘掉有多难 2021-01-20 06:52

I have a database of Transactions (Access 2007) that are recorded in hourly, daily and monthly intervals. I would like to view them in a meaningful way (instead of hour-by-

相关标签:
5条回答
  • 2021-01-20 07:15

    I generally use Format([TransactionDate], "yyyy-mm") because it's simple and sorts well.
    As another option, you could use [TransactionDate]-Day([TransactionDate])+1, which will move every date to the first of its month. THe advantage is that you can still easily format that any way you want, or group that by quarter or year afterwards.

    0 讨论(0)
  • 2021-01-20 07:24

    So as to Avoid conversion to strings, concatenations and conversion back to dates, use DATEADD() and DATEDIFF().

    SELECT
      DATEADD("m", DATEDIFF("m", 0, TransactionDate), 0) AS TransactionMonth,
      SUM(Usage)                                         AS TotalUsage
    FROM
      yourTable
    WHERE
      TransactionDate BETWEEN <startDate> AND <endDate>
    GROUP BY
      DATEADD("m", DATEDIFF("m", 0, TransactionDate), 0)
    ORDER BY
      DATEADD("m", DATEDIFF("m", 0, TransactionDate), 0)
    
    0 讨论(0)
  • 2021-01-20 07:36

    something like...

    SELECT Month(UsageTable.TransactionDate) & '/' & Year(UsageTable.TransactionDate) AS BillingPeriod, Sum(UsageTable.Usage) AS Usage
    FROM UsageTable
    WHERE (((UsageTable.TransactionDate) Between [Some Start Date] And [Some End Date]))
    GROUP BY Month(UsageTable.TransactionDate) & '/' & Year(UsageTable.TransactionDate);
    
    0 讨论(0)
  • 2021-01-20 07:37

    It seems that you would need to group by both the month and the year. Otherwise, you'll have January 2010 and January 2011 combined:

    SELECT YEAR(TransactionDate), MONTH(TransactionDate), SUM(Usage)
    FROM YourTable
    WHERE (TransactionDate Between [Some Start Date] AND[Some End Date])
    GROUP BY YEAR(TransactionDate), MONTH(TransactionDate)
    ORDER BY YEAR(Created), MONTH(Created)
    

    I don't know if your version of SQL has the MONTH and YEAR functions, so you may have to use DATEPART.

    0 讨论(0)
  • 2021-01-20 07:37
    SELECT MONTH(TransactionDate),YEAR(TransactionDate), SUM(Usage) 
    FROM UsageTable 
    Where (TransactionDate Between [Some Start Date] AND[Some End Date]) 
    GROUP BY MONTH(TransactionDate),YEAR(TransactionDate);
    
    0 讨论(0)
提交回复
热议问题