当存在多个日期时,从最高日期查找id

时间:2013-03-28 10:05:23

标签: sql date inner-join max multiple-tables

当我运行此查询时,我得到:

SELECT DISTINCT r2.ApplicationBK,
                max(r2.DatumApplication) maxdatum,
                p.Name
FROM FCT_Recruitment r2,
     DIM_WervingsProject wp,
     DIM_Persoon p
WHERE r2.WervingsProjectID = wp.WervingsProjectID
  AND r2.PersoonID=p.PersoonID
GROUP BY ApplicationBK,
         p.name

这些名字位于TALBLE DIM_PERSOON P
中 “ApplicationBK”位于DIM_Wervingsproject中 所有日期(DatumAppliocation)都在FCT_Recruitment

BK  -  Date - Name 
012    20-03-1999  - name1 
023    21-03-1999  - name1 
033    22-03-1999  - name1 
112    20-03-1990  - name2 
123    20-03-1999  - name2 
133    20-03-1990  - name2

但是我需要每个名字的最高日期..所以每个名字只能在'name-column'中站立一次,并带有相应的id(ApplicationBK)和日期。我不需要休息。

如果这不起作用我尝试了其他的东西......

SELECT WervingsprojectBK,
       r.ApplicationBK,
       p.Name,
       count(*) number,upper(r.StatusWP) status,
                       upper(r.StatusApplication)statusdetail,
                       r.DateApplication 
FROM FCT_Recruitment AS r,
     DIM_WervingsProject wp,
     DIM_Persoon p
INNER JOIN
  (SELECT DISTINCT r2.ApplicationeBK,
                   max(r2.DateApplication) maxdatum
   FROM FCT_Recruitment r2,
        DIM_WervingsProject wp,
        DIM_Persoon p
   WHERE r2.WervingsProjectID=wp.WervingsProjectID
     AND r2.PersoonID=p.PersoonID
   GROUP BY ApplicationBK) AS r2 ON (r.ApplicationBK=r2.ApplicationBK
                                     AND r.DateApplication=r2.maxdatum)
GROUP BY WervingsprojectBK,
         r.ApplicationBK,
         p.Naam,
         r.StatusApplication,
         r.StatusWP
ORDER BY 5

然后我得到这些错误..:

  

消息4104,级别16,状态1,行3多部分标识符   “r.ApplicationBK”无法绑定。   Msg 4104,Level 16,State   1,第3行   多部分标识符“r.DateApplication”可以   不受约束。

你能帮忙帮忙吗? 感谢。

2 个答案:

答案 0 :(得分:0)

请改为尝试:

select 
  r2.ApplicationBK, 
  r22.maxdatum, 
  p.Name
from FCT_Recruitment r2
INNER JOIN
(
  SELECT WervingsProjectID, max(r2.DatumApplication) maxdatum
  FROM FCT_Recruitment
  GROUP BY WervingsProjectID
) AS r22  ON r2.WervingsProjectID = r22.WervingsProjectID
         AND r2.DatumApplication  = r22.maxdatum
INNER JOIN DIM_WervingsProject AS wp ON r2.WervingsProjectID = wp.WervingsProjectID
INNER JOIN DIM_Persoon         AS p  ON r2.PersoonID         = p.PersoonID;

答案 1 :(得分:0)

试试这个。并更改列名称:

SELECT max(r.AllDate),r.ProjectID,p.name 
FROM FCT_Recruitment r,DIM_Wervingsproject pr, DIM_PERSOON p 
where p.PID=r.PID and r.ProjectId=pr.ProjectID 
group by r.PID;