MSSQL中2个搜索结果集相减如何实现?

来源:百度知道 编辑:UC知道 时间:2024/05/13 20:07:31
请问MSSQL中2个搜索结果集相减如何实现?
例如在table1中我想检索出只缴过一次费用的人,如下表:
stdnum times name money
121 1 李明 200
122 1 小刚 300
123 1 黄红 400
122 2 小刚 300
121 2 李明 500
121 3 李明 100
符合要求的只有stdnum为123的黄红。方法是先检索times=1的所有stdnum,然后检索times=2的所有stdnum,然后用结果集1减去结果集2,就可以得出结果。请问在MSSQL里面什么语句可以实现这种结果相减?
1楼的我不太明白……
2楼的答案……这样检索出来的结果跟select * from table1 where times='1'有什么区别?

花了10分钟终于写好了

试试看

declare @mytest int,@mytest2 int,@mytest3 int

set @mytest=(select sum(stdnum) from table1 where times=1)

set @mytest2=(select sum(stdnum) from table1 where times=2)

set @mytest3=abs(@mytest-@mytest2)

select * from table1 where stdnum=@mytest3

为什么不这样检索呢
select * from table1 where times=1 and times<>2

select * into #temp1 from table1 where 条件1

select * into #temp2 from table1 where 条件2

select * from #temp1 where id not in (select id from #temp2 )

或者不考虑效率,直接写成
select * from tale1 where id not in (select id from tabel1 where 条件2) and 条件1