选择适当的记录

时间:2018-09-17 18:16:01

标签: sql ms-access

我需要有关此查询的帮助:

SELECT Max(UQ.rcd_num) AS Max_RCD_NUM, 
       UQ.emp_id, 
       UQ.pperiod, 
       UQ.prun, 
       UQ.pc, 
       UQ.amount 
FROM   time1 AS UQ 
GROUP  BY UQ.emp_id, 
          UQ.pperiod, 
          UQ.prun, 
          UQ.pc, 
          UQ.amount; 

它读取以下数据: enter image description here

它给了我这个结果: enter image description here

但是我希望红色标记的数据仅在此特定示例中使用Max_RCD_NUM 9224而不是Max_RCD_NUM 7972记录。

此查询稍后用作该查询的子查询:

SELECT time1.* 
FROM   time1 
       INNER JOIN query3 AS TIMEAGG 
               ON ( [time1].[pperiod] = TIMEAGG.pperiod ) 
                  AND ( [time1].[prun] = TIMEAGG.prun ) 
                  AND ( [time1].[emp_id] = TIMEAGG.emp_id ) 
                  AND ( [time1].[pc] = TIMEAGG.pc ) 
                  AND ( [time1].[rcd_num] = TIMEAGG.max_rcd_num ); 

您能帮我解决我的第一个查询,以便它针对特定的PPERIOD和特定的EMP_ID只选择一个Max_RCD_NUM最高的记录吗?

2 个答案:

答案 0 :(得分:0)

当您需要特定Max_RCD_NUM和特定PPERIOD最高EMP_ID的记录时,只应按PPERIODEMP_ID进行分组。在您的示例中,您可以通过简单地删除分组条件amount来解决查询问题,因为它在具有Max_RCD_NUM 9224(数量= 1725)和Max_RCD_NUM 7972(数量= 1840)的行中有所不同。

SELECT Max(UQ.rcd_num) AS Max_RCD_NUM, 
       UQ.emp_id, 
       UQ.pperiod, 
       UQ.prun, 
       UQ.pc
FROM   time1 AS UQ 
GROUP  BY UQ.emp_id, 
          UQ.pperiod, 
          UQ.prun, 
          UQ.pc; 

答案 1 :(得分:0)

您可以使用相关子查询。您想要做的是过滤,而不是汇总:

SELECT uq.*
FROM time1 as uq
WHERE uq.RCD_NUM = (SELECT MAX(uq2.RCD_NUM)
                    FROM time1 as uq2
                    WHERE uq2.emp_id = uq.emp_id and uq2.pperiod = uq.pperiod
                   );