Привет, я думаю, вы можете создать запрос с использованием CTE следующим образом:
Ресурс: CTE Microsoft: https://docs.microsoft.com/fr-fr/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15
Или используя форму select in clause
РЕДАКТИРОВАТЬ: Или он работает с вашим текущим запросом на
create Table #EMPLOYEE
(
EMP_ID INT,
EMP_NAME varchar(128)
)
create Table #HOLIDAYS
(
HL_ID INT,
HL_EMP varchar(128),
StartDate DATE,
EndDate DATE
)
Insert into #EMPLOYEE
(
EMP_ID,
EMP_NAME
)
SELECT 1, 'Toto'
UNION ALL
SELECT 2,'Dupont'
UNION ALL
SELECT 3,'Titi'
UNION ALL
SELECT 4,'Tata'
Insert into #HOLIDAYS
(
HL_ID,
HL_EMP,
StartDate,
EndDate
)
SELECT '1', '1',GETDATE(),DATEADD(day,4,GETDATE())
UNION ALL
SELECT '2','1',DATEADD(day,-7,GETDATE()), DATEADD(day,-5,GETDATE())
UNION ALL
SELECT '3','2',DATEADD(day,4,GETDATE()),DATEADD(day,15,GETDATE())
-- USING CTE EXEMPLE
;WITH MyCteAPP AS (
SELECT EMP_ID, EMP_NAME, HL_ID, ISNULL(StartDate,GETDATE()) AS 'StartDate', ISNULL(EndDate,GETDATE()) AS 'EndDate'
FROM #EMPLOYEE
LEFT JOIN #HOLIDAYS ON EMP_ID = HL_EMP
)
SELECT EMP_ID, EMP_NAME, SUM(DATEDIFF(day,StartDate,EndDate)) AS 'NbDay'
FROM MyCteAPP
GROUP BY EMP_ID,EMP_NAME
ORDER BY EMP_ID
-- USING SELECT IN FROM EXEMPLE
SELECT EMP_ID, EMP_NAME, SUM(DATEDIFF(day,StartDate,EndDate)) AS 'NbDay'
FROM (SELECT EMP_ID, EMP_NAME, HL_ID, ISNULL(StartDate,GETDATE()) AS 'StartDate', ISNULL(EndDate,GETDATE()) AS 'EndDate'
FROM #EMPLOYEE
LEFT JOIN #HOLIDAYS ON EMP_ID = HL_EMP
) AS SUBQUERY
GROUP BY EMP_ID,EMP_NAME
ORDER BY EMP_ID
--USING CURRENT QUERY
SELECT EMP_ID, EMP_NAME, SUM(DATEDIFF(day,ISNULL(StartDate,GETDATE()),ISNULL(EndDate,GETDATE()))) AS 'NbDay'
FROM #EMPLOYEE
LEFT JOIN #HOLIDAYS ON EMP_ID = HL_EMP
GROUP BY EMP_ID,EMP_NAME
ORDER BY EMP_ID
DROP TABLE #EMPLOYEE
DROP TABLE #HOLIDAYS
РЕЗУЛЬТАТ: