Share via

How to display last 3 quarters from getdate() like ex: YYYYQ1,YYYYQQ,YYQQ

MSBI_Developer_1990 41 Reputation points
2023-02-14T11:31:19.17+00:00

Hi Folks,

Thanks in advance .

i want to display last three quarters dynamically. if i give getdate() today it should show 2023Q1, 2022Q4,2022Q3.

Can you please help me how achieve this.

Thank again.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


4 answers

Sort by: Most helpful
  1. LiHongMSFT-4306 31,621 Reputation points
    2023-02-15T07:16:27.55+00:00

    Hi @MSBI_Developer_1990

    Here is a sample you might refer to: code.txt

    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.

    Was this answer helpful?

    0 comments No comments

  2. LiHongMSFT-4306 31,621 Reputation points
    2023-02-15T06:56:21.6933333+00:00

    Hi @MSBI_Developer_1990

    i want to display last three quarters dynamically.

    Not sure what you actually want.

    If you just want to display the three previous quarters, then experts had provided solutions above.

    If you need to display column headings dynamically, for example, always display last 3 quarters data according to query date. Then you'd better share us your table structure (CREATE TABLE …) and some sample data (INSERT INTO …) along with your expected result.

    Best regards,

    Cosmog Hong

    Was this answer helpful?

    0 comments No comments

  3. Jingyang Li 5,901 Reputation points Volunteer Moderator
    2023-02-14T16:41:31.0266667+00:00

    Please try the following:

    
    
    DECLARE @dt datetime = getdate()
    
     select  Concat(DATEPART(year, DATEADD(QUARTER,-n,@dt)),'Q',DATEPART(QUARTER, DATEADD(QUARTER,-n,@dt)) )
     from (values(0),(1),(2)) d(n)  
      
      select string_agg( Concat(DATEPART(year, DATEADD(QUARTER,-n,@dt)),'Q',DATEPART(QUARTER, DATEADD(QUARTER,-n,@dt)) ) ,',')
     from (values(0),(1),(2)) d(n)    
    
    

    Was this answer helpful?

    0 comments No comments

  4. Naomi Nosonovsky 8,906 Reputation points
    2023-02-14T14:07:25.4+00:00

    Try:

    DECLARE @d1 date = DATEADD(QUARTER,-1, CURRENT_TIMESTAMP)
    DECLARE @d2 date = DATEADD(QUARTER,-2, CURRENT_TIMESTAMP)
    SELECT FORMAT(@d1, 'yyyy') + CONCAT('Q', DATEPART(QUARTER,@d1)) AS Previous ,
    FORMAT(@d2, 'yyyy') + CONCAT('Q', DATEPART(QUARTER,@d2)) AS [2 Quarters Back]
    
    

    Was this answer helpful?

    0 comments No comments

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.