无法弄清楚如何显示工作年数(包括少于4年)

时间:2017-04-24 12:53:55

标签: sql sqlyog

我目前有这个问题,而且我试图弄清楚如何在查询的最后四(4)年内修复加入。任何帮助,将不胜感激。感谢

问题: 列出所有医生,这些医生是目前活跃的诊所医生,在过去四(4)年内是女性和加入。显示医生的姓名和主管的姓名。

当前查询:

SELECT  CONCAT(d.given, d.surname) AS Doctor_Name, 
CONCAT(s.given, s.surname) AS Supervisor_Name
FROM doctor d, doctor s
WHERE s.doctorid = d.supervisorid 
AND d.resigned IS NULL 
AND d.sex = 'f' 
AND YEAR(d.joined) > 2013

选项2

SELECT CONCAT(doc.given,' ',doc.surname) AS Doctor_Name, 
CONCAT(sup.given,' ',sup.surname) AS Supervisor_Name,
doc.sex, 
doc.joined
FROM doctor doc, doctor sup
WHERE sup.doctorid = doc.supervisorid 
AND doc.resigned IS NULL 
AND doc.sex = 'F' 
AND YEAR (doc.joined) >= YEAR(CURRENT_DATE - INTERVAL 4 YEAR)
ORDER BY doc.joined

1 个答案:

答案 0 :(得分:0)

SELECT  
   CONCAT(d.given, d.surname) AS Doctor_Name, 
   CONCAT(s.given, s.surname) AS Supervisor_Name
FROM doctor d
JOIN doctor s
   ON s.doctorid = d.supervisorid 
WHERE 
   d.resigned IS NULL 
   AND d.sex = 'f' 
   AND DATEDIFF(YEAR,d.joined,GETDATE()) < 4

所以重点在于

DATEDIFF(YEAR,d.joined,GETDATE()) < 4

将从GETDATE()中减去d.joined的年份,因此如果加入的是2015-01-01而GETDATE()返回2017-01-01,则结果将为2。 如果您想要从现在开始4年后就必须这样做

DATEDIFF(DAY,d.joined, GETDATE()) < 4*365

这是近似正确的,但如果我们跨越一个世纪的边界,或者如果时间段是4年以外的其他时间,则不能很好地处理闰年。