Query to average numbers from specific months?

pilotguy251 20 Reputation points
2023-05-17T00:25:18.1366667+00:00

Hello, I am trying to create a query that will average the numbers from specific months. More detailed, I would like the query to pull the numbers from January 2021, January 2022, and January 2023, add them, then divide by three to get 16021. If this has to be done in a couple of different steps, that's fine. I was just looking for some extra input as I have reached somewhat of a roadblock.

Thank you

1

SQL Server | Other
{count} votes

Answer accepted by question author
  1. LiHongMSFT-4306 31,616 Reputation points
    2023-05-17T01:30:29.9766667+00:00

    Hi @pilotguy251

    Try this:

    Declare @temp table(ID INT identity(1,1), T_Date Datetime,Number int)
    insert into @temp values
    ('2021-01-01',16316),('2021-02-01',14860),
    ('2022-01-01',16051),('2022-02-01',15051),
    ('2023-01-01',15696),('2023-02-01',14797)
    
    DECLARE @Month INT
    SET @Month=1
    
    SELECT AVG(Number) AS Jan_Avg
    FROM @temp
    WHERE MONTH(T_Date) = @Month
    
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.