Hi ,Please try below if it's match with your desire result..
May be it can be done with more simply way.
I have alterd function alldays to include startdate for join.
ALTER FUNCTION [dbo].[AllDays] (@startdate DATETIME, @enddate DATETIME)
RETURNS @alldays TABLE
(
startdate DATETIME,
datum DATETIME
)
AS
BEGIN
DECLARE @i DATETIME
SELECT @i = @startdate
WHILE @i <= @enddate
BEGIN
INSERT INTO @alldays
(
startdate,
datum
)
VALUES
(
@startdate,
@i
)
SELECT @i = @i + 1
END
RETURN
END
GO
DECLARE @enddate DATETIME
SET @enddate = '2014-08-31'
SELECT H.res_id,
fullname,
WSL.DayStart,
WSL.StartDate,
WSL.ShiftID,
T.datum AS DATEFIELD,
(
SELECT MAX(WeekDay)
FROM WorkSchedules
WHERE ShiftID = WSL.ShiftID
)
AS MAXDAYSSCHEDULE,
CASE
WHEN ABS(DATEDIFF(DAY, WSL.StartDate, T.datum)) + WSL.DayStart <=
(
SELECT MAX(WeekDay)
FROM WorkSchedules
WHERE ShiftID = WSL.ShiftID
)
THEN ROW_NUMBER() OVER (PARTITION BY (DATEDIFF(DAY, WSL.StartDate, T.datum) + WSL.DayStart - 1) /
(
SELECT MAX(WeekDay)
FROM WorkSchedules
WHERE ShiftID = WSL.ShiftID
), Res_id ORDER BY DATEDIFF(DAY, WSL.StartDate, T.datum) ,Res_id)+wsl.DayStart-1
ELSE ROW_NUMBER() OVER (PARTITION BY (DATEDIFF(DAY, WSL.StartDate, T.datum) + WSL.DayStart - 1) /
(
SELECT MAX(WeekDay)
FROM WorkSchedules
WHERE ShiftID = WSL.ShiftID
), Res_id ORDER BY DATEDIFF(DAY, WSL.StartDate, T.datum) , Res_id)
END [Counter]
FROM humres H
LEFT JOIN workschedulelinks WSL ON H.res_id = WSL.Resource
AND WSL.EndDate IS NULL
CROSS APPLY [dbo].[AllDays](WSL.StartDate, @enddate) T
WHERE T.startdate = WSL.StartDate
--and h.res_id IN (79, 233, 321) --= 1131901
ORDER BY Res_ID,
DATEFIELD