我有两张桌子:
Table 1
id date
1 01-JAN-2011
2 01-JAN-2011
3 01-JAN-2011
Table 2
id index
1 01
1 05
1 06
2 01
2 02
3 01
3 07
我正在尝试列出所有id-number一次,其中没有索引号06或07在该id的任何条目中。因此,在这种情况下,例如,我应该只得到id 2。表1我需要用于日期搜索。
答案 0 :(得分:3)
SELECT DISTINCT id
FROM table2 t
WHERE NOT EXISTS (SELECT NULL
FROM table2
WHERE t.id = id
AND index IN ('06', '07'))
答案 1 :(得分:1)
通常最好发布实际的表定义/插入语句,以便人们可以编写和测试他们的解决方案。这是我的尝试,使用下面的示例表:
select ID from T2
except
select ID from T2 where Indx in ('06','07')
这已在SQL Server 2008中测试过。
示例表:
create table T2 (
ID int not null,
Indx char(2) not null
)
go
insert into T2(ID,Indx)
select 1,'01' union all
select 1,'05' union all
select 1,'06' union all
select 2,'01' union all
select 2,'02' union all
select 3,'01' union all
select 3,'07'
go
答案 2 :(得分:0)
名义上,根据您指定的条件,表1并不重要:
SELECT DISTINCT t2.id
FROM Table2 AS t2
WHERE t2.id NOT IN (SELECT DISTINCT t2a.id
FROM Tble2 AS t2a
WHERE t2a.index IN('06', '07')
);
但是,如果您只想要与表1中的id匹配的条目,则:
SELECT DISTINCT t1.id
FROM Table1 AS t1
JOIN (SELECT DISTINCT t2.id
FROM Table2 AS t2
WHERE t2.id NOT IN (SELECT DISTINCT t2a.id
FROM Tble2 AS t2a
WHERE t2a.index IN('06', '07')
)
) AS t3
ON t1.id = t3.id;
请注意,我将索引编码为字符串'06','07',因为如果索引实际上是数字列,则前导零是无关紧要的。如果您的Table.Index列实际上是某种数字类型,请删除引号和前导零;它甚至可以给你(略微)更好的表现。