Create a Variable to store how many employees have been employed with the company for more than 3 years
If you want to set a variable to a count, you have two problems:
- Your subquery has more than one column.
- Your subquery probably returns more than one row.
You can use:
SET @EmployeeLengthAfterHire = (
SELECT COUNT(*)
FROM HospitalStaff
WHERE DATEDIFF(YEAR, HireDate, GETDATE()) > 3
)
That said, your query is not calculating more than 3 years. It is calculating the number of year boundaries between two dates. So, 2019-12-31 and 2020-01-01 would be "1" year apart by this logic.
I would recommend:
SET @EmployeeLengthAfterHire = (
SELECT COUNT(*)
FROM HospitalStaff
WHERE HireDate < DATEADD(YEAR, -3, HireDate)
);
I'm not sure why you named the column "EmployeeLengthAfterHire".