按最近日期过滤查询结果

时间:2013-09-10 17:03:38

标签: sql ms-access

此代码:

SELECT  
    O896IA_VEMPPRSA.REG_NR & O896IA_VEMPPRSA.DIS_NR AS RRDD,  
    Mgmt_Lvl.MGMT_LVL,  
    Count(O896IA_VEMPPRSA.SYS_EMP_ID_NR) AS Total,  
    Sum(IIf(emp_rlc_ir="Y",1,0)) AS Relocate,  
    Sum(IIf(emp_int_asn_ir="Y",1,0)) AS International_Assignment,  
    Sum(IIf(emp_tvl_ir="y",1,0)) AS Travel,  
    Sum(IIf(emp_spc_asn_ir="y",1,0)) AS Special_Assignment,  
    Sum(IIf([emp_rlc_ir]="Y",1,0))/[Total] AS Relocate_Percent,  
    Sum(IIf([emp_int_asn_ir]="Y",1,0))/[Total] AS International_Assignment_Percent,  
    Sum(IIf([emp_tvl_ir]="y",1,0))/[Total] AS Travel_Percent,  
    Sum(IIf([emp_spc_asn_ir]="y",1,0))/[Total] AS Special_Assignment_Percent

FROM (O867IA_VPJOBCO INNER JOIN Mgmt_Lvl  
    ON O867IA_VPJOBCO.JOB_GRP_CD = Mgmt_Lvl.JOB_GRP_CD)  
INNER JOIN (O896IA_VEMPPRSA INNER JOIN O867IA_VCAREER  
    ON O896IA_VEMPPRSA.SYS_EMP_ID_NR = O867IA_VCAREER.SYS_EMP_ID_NR)  
    ON O867IA_VPJOBCO.JOB_CLS_CD = O896IA_VEMPPRSA.JOB_CLS_CD

WHERE (((O896IA_VEMPPRSA.EMP_EMT_STS_CD)<>"T"))

GROUP BY  
    O896IA_VEMPPRSA.REG_NR & O896IA_VEMPPRSA.DIS_NR, 
    Mgmt_Lvl.MGMT_LVL,  
    Mgmt_Lvl.Ranking

ORDER BY Mgmt_Lvl.Ranking DESC;

给了我员工的调查答案,问题是这项调查是每年进行的,我需要最近几年的答案。

我尝试将MAX用于REC_EFF_STT_DT但是对于一些员工来说,他们的答案每年都会改变,所以由于分组(我需要),它仍然会返回多年答案。

是否有解决方案我可以提取最新数据?如果一名员工在2008年,2009年和2010年参加调查而不是在2011年,2012年或2013年,则不一定必须是2013年,那么我仍然希望2010年的数据,这是他们所采取的最新调查是什么我需要。

1 个答案:

答案 0 :(得分:1)

假设您有一个名为[Survey]的表格,其中包含以下数据

RespondentID    SurveyDate  Answer1                         Answer2
------------    ----------  ----------------------------    ----------------------------
1               2013-01-01  answer 1, respondent 1, 2013    answer 2, respondent 1, 2013
1               2012-01-01  answer 1, respondent 1, 2012    answer 2, respondent 1, 2012
2               2012-01-01  answer 1, respondent 2, 2012    answer 2, respondent 2, 2012

您可以使用表单的查询...

SELECT Survey.*
FROM
    Survey
    INNER JOIN
    (
        SELECT RespondentID, MAX(SurveyDate) AS MaxOfSurveyDate
        FROM Survey
        GROUP BY RespondentID
    ) AS MaxDate
        ON Survey.RespondentID = MaxDate.RespondentID
            AND Survey.SurveyDate = MaxDate.MaxOfSurveyDate

...返回每个受访者的最新行,在这种情况下将是:

RespondentID    SurveyDate  Answer1                         Answer2
------------    ----------  ----------------------------    ----------------------------
1               2013-01-01  answer 1, respondent 1, 2013    answer 2, respondent 1, 2013
2               2012-01-01  answer 1, respondent 2, 2012    answer 2, respondent 2, 2012