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
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With