[英]SQL - Comparing against multiple values in the same column?
Ok, so I'm trying to write some SQL and I'm not sure how to tackle this situation.好的,所以我正在尝试编写一些 SQL,但我不确定如何解决这种情况。 I have a table similiar to what is below.
我有一张类似于下面的表格。 The basic idea is that I need to get the records that are in an 'H' status (easy enough), but I need to exclude records that were in an 'H' status and moved on to an 'A' status at a later date.
基本思想是我需要获取处于“H”状态的记录(足够简单),但我需要排除处于“H”状态并稍后转移到“A”状态的记录日期。
So ideally, the results should only return the last two records, IDs 03 and 04. How would you guys do this?所以理想情况下,结果应该只返回最后两个记录,ID 03 和 04。你们会怎么做?
ID STATUS STAT_DATE
01 A 05/01/2013
01 H 05/01/2012
02 A 12/01/2013
02 H 12/01/2012
03 H 03/01/2009
04 H 02/01/2008
You could do it this way:你可以这样做:
select *
from t t1
where status='H' and not exists(
select *
from t t2
where t1.id=t2.id and t2.status='A' and t2.stat_date > t1.stat_date)
That will give you all entries of table t with status='H' where there is no entry in t with the same id, a later date, and status='A'.这将为您提供表 t 中 status='H' 的所有条目,其中 t 中没有具有相同 ID、较晚日期和 status='A' 的条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.