Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get last 4 Quarters with last 2 digit of Year

I need to get the last 4 records from a table and it has records with column value like '19Q1','18Q4'.

using below query I can get last 4 quarters but is there any simplest form of this query.

SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,0,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,0,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-1,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-1,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-2,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-2,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-3,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-3,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period

O/P:

1Q19
4Q18
3Q18
2Q18
like image 212
Tech Learner Avatar asked Mar 04 '23 11:03

Tech Learner


2 Answers

Assuming you're using 2012 (because you've tagged 3 different versions of SQL Server...) How about:

SELECT CONCAT(DATEPART(QUARTER,Q.D),'Q',RIGHT(DATEPART(YEAR,Q.D),2))
FROM (VALUES(0),(-1),(-2),(-3)) V(i)
     CROSS APPLY (VALUES(DATEADD(QUARTER,V.i,GETDATE()))) Q(D);
like image 105
Larnu Avatar answered Mar 07 '23 00:03

Larnu


SELECT CAST( DATEPART(q, DATEADD(q, -v.num, d.CurrentDate) ) AS VARCHAR(1)) 
+ 'Q'
+ RIGHT( CAST( DATEPART(yyyy, DATEADD(q, -v.num, d.CurrentDate)) AS VARCHAR(4) ), 2 )
FROM ( VALUES ( GETDATE() ) ) d(CurrentDate)
    CROSS JOIN ( VALUES (0), (1), (2), (3) ) v(num)
ORDER BY DATEADD(q, -v.num, d.CurrentDate) DESC
like image 21
Denis Rubashkin Avatar answered Mar 07 '23 00:03

Denis Rubashkin