我需要有关此查询的帮助:
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;
但是我希望红色标记的数据仅在此特定示例中使用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最高的记录吗?
答案 0 :(得分:0)
当您需要特定Max_RCD_NUM
和特定PPERIOD
最高EMP_ID
的记录时,只应按PPERIOD
和EMP_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
);