下面显示的是COMPANY表,我想提取特定ID的最新唯一DEPT行记录。下面提到了实现这一要求的算法。我面临的问题是,我无法弄清算法中嵌入为嵌套查询的第3步。请建议。
ID STATE DEPT DATETIME yr_mon_date
================================================================
A8178 state2 Account 2016:09:01 14:11:44 2016:09:01
A8178 state3 Account 2016:09:01 15:12:50 2016:09:01
A8178 state3 Account 2016:09:01 16:11:33 2016:09:01
A8178 state3 Sales 2016:09:01 18:19:34 2016:09:01
A8178 state2 Sales 2016:09:01 18:28:50 2016:09:01
A8178 state3 Sales 2016:09:01 18:35:22 2016:09:01
select ID, STATE, DEPT, DATETIME, substr(DATETIME, 1, 10) yr_mon_date from COMPANY t1
where (STATE = 'state1' or STATE = 'state2' or STATE = 'state3' ) and
yr_mon_date = '2016:09:01' and DEPT = 'Sales' and DATETIME =
(select max(t2.DATETIME) from COMPANY t2 where t2.ID = t1.ID );
ID STATE DEPT DATETIME yr_mon_date
================================================================
A8178 state3 Account 2016:09:01 16:11:33 2016:09:01
A8178 state3 Sales 2016:09:01 18:35:22 2016:09:01
答案 0 :(得分:0)
你的算法错了。 您希望按DEPT检索每个ID的最新记录。 您可以使用子查询中的MAX函数检索最近的事务。 并且通过在子查询中加入这些列,每个DEP的ID。
SELECT ID, STATE, DEPT, DATETIME
FROM COMPANY t1
WHERE DATETIME =
(
SELECT MAX(t2.DATETIME)
FROM COMPANY t2
WHERE t2.ID = t1.ID
AND t2.DEPT = t1.DEPT
)