Click here to Skip to main content
15,916,951 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a data with date field which has first of month of each the quarter (2021-01-01 then 2021-04-01 etc..) interval of considered as every 3 months like 10, 1, 4 in a year.
I am currently getting the previous qtr. data by mentioning the start of previous quarter date as 2021-04-01.

How to get the previous qtr. data when i am in current quarter without mentioning the date in query LIKE MENTIONED BELOW

Example: WHERE Region IN ('Africa') AND Date ='2021-04-01'

I am trying to achieve this using SQL

What I have tried:

I couldn't find a way to do it...
Posted
Updated 23-Oct-22 2:32am

1 solution

Taken this is SQL Server you can use DATEDIFF and DATEADD in your query. Consider the following example
SQL
select DATEADD( QUARTER, DATEDIFF( QUARTER, 0, GETDATE()) - 1, 0) AS StartDate,
       DATEADD( QUARTER, DATEDIFF( QUARTER, 0, GETDATE()), 0) - 1 AS EndDate

So in your where condition it could be something like the following if the quarter is precalculated into the data
SQL
SELECT ...
FROM ...
WHERE DateField = DATEADD( QUARTER, DATEDIFF( QUARTER, 0, GETDATE()) - 1, 0)
...

Or following if you just have different dates in the data
SQL
SELECT ...
FROM ...
WHERE DateField BETWEEN DATEADD( QUARTER, DATEDIFF( QUARTER, 0, GETDATE()) - 1, 0)
                AND     DATEADD( QUARTER, DATEDIFF( QUARTER, 0, GETDATE()), 0) - 1
...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900