Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Extract data for last day of previous months

Author  Topic 

prodiguy02
Starting Member

1 Post

Posted - 2014-06-12 : 02:40:30
Hi all,

I need to extract records for the last day of previous months (Up till January of the same year) from a table SALES, according to a date parameter ASOFDATE that the user enters.

For Example

If user keys in ASOFDATE as 10-May-2014, I would have

ASOFDATE Data1 Data2
10-MAY-2014 123 443
30-APR-2014 222 234
31-MAR-2014 544 875
28-FEB-2014 546 908
31-JAN-2014 957 896

How do I do that? Kindly advice!

prodiguy

MuralikrishnaVeera
Posting Yak Master

129 Posts

Posted - 2014-06-12 : 04:20:29
First you should have a calender table and need to perform manipulations based on the outcome

---------Script to Populate Calender Table------------

DECLARE @TEMP VARCHAR(50) = '2014-01-01'
DECLARE @TEMP1 VARCHAR(50)= '2014-12-31'
;WITH Calender AS
(
SELECT CAST(@TEMP AS DATETIME) StartDate
UNION ALL
SELECT StartDate + 1
FROM Calender
WHERE StartDate + 1 <= @TEMP1
)
SELECT * INTO #temp
FROM (
SELECT CAST(CONVERT(CHAR(8),CAST(StartDate AS DATETIME),112) AS INT) AS DateKey
, StartDate
, DATEPART(DW, StartDate) AS DayNumberOfWeek
, DATENAME(DW, StartDate) AS EnglishDayNameOfWeek
, DAY (StartDate) AS DayNumberOfMonth
, DATEPART(DY, StartDate) AS DayNumberOfYear
, DATEPART(WK, StartDate) AS WeekNumberOfYear
, DATENAME(MM, StartDate) AS EnglishMonthName
, MONTH (StartDate) AS MonthNumberOfYear
, DATEPART(QQ, StartDate) AS CalendarQuarter
, YEAR (StartDate) AS CalendarYear
, (CASE WHEN MONTH(StartDate)>=1 AND MONTH(StartDate) <=6 THEN 1 ELSE 2 END) AS CalendarSemester
FROM Calender
)x
OPTION (MAXRECURSION 0)

GO
--------Your Required Dates ------------------

DECLARE @AsofDate varchar(max) = '2014-05-10'
SELECT CONVERT(CHAR(128), MAX(StartDate), 6 ) AS Dates FROM #temp WHERE StartDate< = @AsofDate GROUP BY MonthNumberOfYear

--------Drop table ---------------------------
DROP TABLE #temp
-----------------------------------------------



---------------
Murali Krishna

You live only once ..If you do it right once is enough.......
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2014-06-12 : 15:46:02
[code]DECLARE @AsOfDate DATETIME = '20140510';

SELECT CASE
WHEN Number = 0 THEN @AsOfDate
ELSE DATEADD(MONTH, DATEDIFF(MONTH, -1, @AsOfDate) - Number, -1)
END
FROM master.dbo.spt_values
WHERE Type = 'P'
AND Number < DATEPART(MONTH, @AsOfDate)[/code]


Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page
   

- Advertisement -