Quarterly data from monthly data in sql server

Learner 226 Reputation points
2022-05-12T12:13:10.3+00:00

Hello All,

I have a table having data like below which has trendtype as monthly.

201512-image.png

Now my requirement is I need to create a query to get quarterly data from the monthly data.
As I have 12 months data here i need to show 4 quarters data.

Could any one please help how to do.
So the new query should have the values TrendType as Quarterly,Date and Sales values.

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 47,436 Reputation points
    2022-05-12T12:19:57.403+00:00

    Use the DATEPART function with parameter QUARTER, like

    select 'Quarterly' as TrendType, min(date) as date, sum(sales) as sales  
    from yourTable  
    group by DATEPART(quarter, date)  
    order by DATEPART(quarter, date)  
    

    See https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-ver15

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-05-12T13:49:12.453+00:00
    create table datatable (TrendType varchar(12), date date, sales int)
    insert into datatable values ('Monthly','5/1/2021',1234),
     ('Monthly','3/1/2021',1234),
      ('Monthly','2/1/2022',1234),
        ('Monthly','5/1/2022',1234),
        ('Monthly','8/1/2021',1234),
       ('Monthly','8/1/2022',1234),
        ('Monthly','12/1/2021',1234),
        ('Monthly','11/1/2022',1234)
    
        select 'Quarterly' TrendType, DATEADD(Q, DATEDIFF(Q, 0, [date]) , 0) as [date],
        Sum(sales) Sales from datatable
        group by  DATEADD(Q, DATEDIFF(Q, 0, [date]) , 0)
        order by DATEADD(Q, DATEDIFF(Q, 0, [date]) , 0)
    
    
        drop table datatable
    
    0 comments No comments

Your answer

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