以下为我提供了相关记录的完整列表:
SELECT ID, NAME, STATE, VDATE, COMPLETE_DATE
from db
where NAME NOT IN (SELECT NAME from db where COMPLETE_DATE != '')
ORDER BY NAME, STATE, VDATE DESC;
不幸的是,我对所有不是最新的记录(根据VDATE)对每个名称都感兴趣。基本上,完全相同的结果MINUS包含最新VDATE的每个名称/状态组合的记录。对于每个名称,状态组合,可能有10条记录,每条记录的VDATE相同或不同。
如何从此数据集中删除最新的VDATE?
答案 0 :(得分:1)
获取每个名称的最大vdate,并在此后使用not in
。
SELECT ID, NAME, STATE, VDATE, COMPLETE_DATE
from db
where (NAME,STATE,VDATE) NOT IN (SELECT NAME,STATE,MAX(VDATE) as MAXVDT
from db
where COMPLETE_DATE != ''
GROUP BY NAME,STATE)
ORDER BY NAME, STATE, VDATE DESC
或使用join
和派生表,其中包含每个名称和州的最大日期。
select d1.ID, d1.NAME, d1.STATE, d1.VDATE, d1.COMPLETE_DATE
from db d1
join (SELECT NAME,STATE,MAX(VDATE) as MAXVDT
from db
where COMPLETE_DATE != ''
GROUP BY NAME,STATE) d2
on d1.name = d2.name and d1.state = d2.state
where d1.vdate <> d2.maxvdt
order by d1.NAME, d1.STATE, d1.VDATE desc
请注意,如果每个名称只有一个vdate,则状态组合两个查询都不会返回结果中的那些名称,状态组合,因为该日期将是该组合的max
vdate。