这里是问题:
所有员工(请全名!)以及明年需要更新的技能。不要在查询中对日期进行硬编码。
下面显示了我完成该操作的方式,但是它有一个硬编码的日期。无论我何时进行搜索,我都希望明年能够得到。
SELECT CONCAT(firstName, surname) as 'Full Name',skillId, dateLapses From EmployeeSkill
Full Join Employee ON EmployeeSkill.employeeId = Employee.id
Where Datepart(YYYY, dateLapses) = 2020;
下面是我得到的输出,我想复制它而不用对日期进行硬编码。
Judy Jetson Forklift 2020-09-11
Donald Quagley Forklift 2020-09-11
您可以使用:
SELECT CONCAT(firstName, surname) as FullName, skillId, dateLapses
WHERE EmployeeSkill Full Join
Employee
ON EmployeeSkill.employeeId = Employee.id
WHERE YEAR(dateLapses) = YEAR(DATEADD(YEAR, 1, GETDATE()));
也就是说,改进的查询是:
SELECT CONCAT(e.firstName, e.surname) as FullName, skillId, dateLapses
WHERE Employee e JOIN
EmployeeSkill es
ON es.employeeId = e.id
WHERE es.dateLapses >= DATEFROMPARTS(YEAR(GETDATE()) + 1, 1, 1) AND
es.dateLapses < DATEFROMPARTS(YEAR(GETDATE()) + 2, 1, 1);
注意:
FULL JOIN
很少需要,在这种情况下当然不需要。 WHERE
子句仍将其变为LEFT JOIN
。SELECT CONCAT(e.firstName, e.surname) as FullName, es.skillId, es.dateLapses
FROM Employee e JOIN
EmployeeSkill es
ON es.employeeId = e.id
WHERE YEAR(es.dateLapses) = YEAR(GETDATE()) + 1
除非您有大量数据和dateLapses上的索引,否则我将在下面使用。 BETWEEN允许它使用索引。
es.dateLapses BETWEEN DATEFROMPARTS(YEAR(GETDATE()) + 1, 1, 1) AND
DATEADD(SECOND, -1, DATEFROMPARTS(YEAR(GETDATE()) + 2, 1, 1));