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
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,291 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]
    
    
    0 comments No comments

  2. Jingyang Li 5,896 Reputation points
    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)    
    
    
    0 comments No comments

  3. LiHongMSFT-4306 31,391 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

    0 comments No comments

  4. LiHongMSFT-4306 31,391 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.

    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.