与最大日期相关的返回值

时间:2017-01-02 19:08:06

标签: sql

我需要返回下面我的Select语句中出现的3个字段,但我只需要与每个FLDREC_NUM的最大日期(FLDDATE)相关联的值(FLDDESCR)。

SELECT FV_OHM_EMPLOYEE.FLDREC_NUM, 
 FV_OHM_FITTEST.FLDDATE,
 FV_OHM_RESPRATR.FLDDESCR 
 FROM   FV_OHM_EMPLOYEE 
 INNER JOIN FV_OHM_FITTEST  
 ON FV_OHM_EMPLOYEE.FLDREC_NUM=FV_OHM_FITTEST.FLDEMPLOYEE 
 INNER JOIN FV_OHM_RESPRATR  
 ON FV_OHM_FITTEST.FLDRESPIRTR=FV_OHM_RESPRATR.FLDCODE

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

SELECT FV_OHM_EMPLOYEE.FLDREC_NUM, 
 FV_OHM_FITTEST.FLDDATE,
 FV_OHM_RESPRATR.FLDDESCR 
 FROM   FV_OHM_EMPLOYEE 
 INNER JOIN FV_OHM_FITTEST  
 ON FV_OHM_EMPLOYEE.FLDREC_NUM=FV_OHM_FITTEST.FLDEMPLOYEE 
 INNER JOIN FV_OHM_RESPRATR  
 ON FV_OHM_FITTEST.FLDRESPIRTR=FV_OHM_RESPRATR.FLDCODE
WHERE
 FV_OHM_FITTEST.FLDDATE = 
   (SELECT DISTINCT MAX(FITTEST_2.FLDDATE)
    FROM FV_OHM_FITTEST FITTEST_2
    WHERE FV_OHM_EMPLOYEE.FLDREC_NUM=FITTEST_2.FLDEMPLOYEE)

答案 1 :(得分:0)

试试这个:

SELECT e.fldrec_num,
  f.flddate,
  r.flddescr
FROM fv_ohm_employee e
INNER JOIN
  (SELECT t1.*
  FROM fv_ohm_fittest t1
  INNER JOIN
    (SELECT fldemployee,
      MAX(flddate) flddate
    FROM fv_ohm_fittest
    GROUP BY fldemployee
    )t2
  ON t1.fldemployee  = t2.fldemployee
  AND t1.flddate     = t2.flddate
  ) f ON e.fldrec_num=f.fldemployee
INNER JOIN fv_ohm_respratr r
ON f.fldrespirtr=r.fldcode