Hi @chavarin chuy
If your SQL Sever support STRING_AGG function, then try this:
DECLARE @YA AS DATETIME = GETDATE();
;WITH CTE AS
(
SELECT *,CASE WHEN [RETARDO] IS NOT NULL THEN LEFT(DATENAME(WEEKDAY,FECHA),1)+':'+CAST([RETARDO] AS VARCHAR(10)) ELSE NULL END AS [Delay]
FROM Datos.dbo.RegistroDeEntradas
CROSS APPLY (values (datediff(minute, cast( isnull(nullif([HORA DE ENTRADA], ''), [RETARDO]) as time), cast([HORA DE SALIDA] as time)))) M(m)
WHERE DATEPART(ISO_WEEK, @YA) = NoSem
)
SELECT EMPLEADO,ID,NoSem
,timefromparts(SUM(m) / 60, SUM(m) % 60, 0, 0, 0) as [HORAS TRABAJADAS]
,STRING_AGG([Delay],',') AS [Delay]
FROM CTE
GROUP BY EMPLEADO,ID,NoSem;
If not, you could use 'STUFF' along with 'FOR XML PATH' instead, like this:
DECLARE @YA AS DATETIME = GETDATE();
;WITH CTE AS
(
SELECT *,CASE WHEN [RETARDO] IS NOT NULL THEN LEFT(DATENAME(WEEKDAY,FECHA),1)+':'+CAST([RETARDO] AS VARCHAR(10)) ELSE NULL END AS [Delay]
FROM Datos.dbo.RegistroDeEntradas
CROSS APPLY (values (datediff(minute, cast( isnull(nullif([HORA DE ENTRADA], ''), [RETARDO]) as time), cast([HORA DE SALIDA] as time)))) M(m)
WHERE DATEPART(ISO_WEEK, @YA) = NoSem
)
SELECT C2.EMPLEADO,C2.ID,C2.NoSem,SUM(C2.m)as [HORAS TRABAJADAS]
,STUFF((SELECT ','+[Delay] FROM CTE C1 WHERE C1.ID = C2.ID FOR XML PATH ('')),1,1,'') AS [Delay]
FROM CTE C2
GROUP BY C2.EMPLEADO,C2.ID,C2.NoSem;
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hi @chavarin chuy
This type of error occured while using DATE|TIMEFROMPARTS
For example, I passed an invalid argument to DATETIMEFROMPARTS (day cannot be 32 in a month & hour cannot be 25 in a day) to above functions. So the constructor of this function cannot create a date from these arguments, so it generates the error.
When you come across this error, please check the arguments passed in the function. The arguments must be valid to avoid this error. It returns a date variable representing the parts. Any NULL input values result in NULL output values. Last but not least, any invalid input results in a ERROR.