我有一张桌子:
HOST_ID | ContractYear
1 | 2008
2 | 2008
3 | 2008
1 | 2009
4 | 2009
我需要的是一个查询,它会告诉我2009年的所有HOST_ID都不是2008年。
上例中的答案是HOST_ID = 4.
感谢。
答案 0 :(得分:2)
select
HOST_ID
from
table_name
where
ContractYear = 2009
AND HOST_ID NOT IN (select HOST_ID from table_name where ContractYear = 2008)
答案 1 :(得分:1)
使用:
SELECT t.host_id
FROM TABLE t
WHERE t.contractyear = 2009
AND NOT EXISTS(SELECT NULL
FROM TABLE t2
WHERE t2.host_id = t.host_id
AND t.contractyear = 2008)
答案 2 :(得分:1)
SELECT DISTINCT host_id
FROM mytable mo
WHERE ContractYear = 2009
AND NOT EXISTS
(
SELECT NULL
FROM mytable mi
WHERE mi.host_id = mo.host_id
AND ContractYear = 2008
)
答案 3 :(得分:1)
更通用,因为它会过滤所有不是您正在寻找的年份
select HOST_ID
from table t
where ContractYear = 2009
and HOST_ID not in (select distinct HOST_ID
from table t2
where t.ContractYear != t2.ContractYear)