Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
Please help me to find the last friday of each month using SQL
Posted

Try this one.

SQL
declare @year int
set @year =2011

-- First and Last Friday
select min(dates) as [First Friday], max(dates) as [Last Friday] from
(
select dateadd(day,number-1,DATEADD(year,@year-1900,0))
as dates from master..spt_values
where type='p' and number between 1 and
DATEDIFF(day,DATEADD(year,@year-1900,0),DATEADD(year,@year-1900+1,0))
) as t
where DATENAME(weekday,dates)='friday'
group by DATEADD(month,datediff(month,0,dates),0)


Best Regards,
@iamsupergrasya
 
Share this answer
 
You can find last Friday from the below Query, i took a dummy day, you can done with the table, where ever you wants.

SQL
DECLARE @dateCol datetime
SELECT @dateCol = GetDate() + 60

SELECT LastWeekDay 
  FROM (
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-1 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-2 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-3 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-4 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-5 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-6 AS LastWeekDay
UNION ALL
SELECT DATEADD(mm,1,@dateCol - DAY(@dateCol)+1)-7 AS LastWeekDay
) AS YourFridayTable
WHERE DATENAME(WeekDay,LastWeekDay) = 'Friday'
 
Share this answer
 
Comments
hasithakaru 22-Feb-12 23:25pm    
Thanks a lot Dhol Gaurav1.
Here is tips for you:
- Find number of days in month.
- Loop step -1 from number of day in month until match Friday.
If you use SQL Server, to find Friday:
SQL
Datepart(weekday,@YourDate)=6
 
Share this answer
 
Comments
hasithakaru 22-Feb-12 21:47pm    
Hi,
Can you explain it further.The question is as follow.

7. Show details of employee hiredates and the date of their first payday. (Paydays occur on the last Friday of each month).

ENAME HIREDATE FIRSTPAYD
---------- --------- ---------
SMITH 17-DEC-80 26-DEC-80
ALLEN 20-FEB-81 27-FEB-81
WARD 22-FEB-81 27-FEB-81
JONES 02-APR-81 24-APR-81
MARTIN 28-SEP-81 25-SEP-81
BLAKE 01-MAY-81 29-MAY-81
CLARK 09-JUN-81 26-JUN-81
SCOTT 09-DEC-82 31-DEC-82
KING 17-NOV-81 27-NOV-81
TURNER 08-SEP-81 25-SEP-81
ADAMS 12-JAN-83 28-JAN-83
JAMES 03-DEC-81 25-DEC-81
FORD 03-DEC-81 25-DEC-81
MILLER 23-JAN-82 29-JAN-82

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