T1: tID, tEvent
001 上课
002 上课
003 上课
004 上课
002 下课
008 下课
T2: tID tCount
001 100
001 90
002 80
002 90
002 10
002 80
003 80
现在需要生成一张新表:
tID tDltCount
001 90
002 90
。。。。。。
输入条件:输入一个tEvent名称,如果,“上课”,根据T1,T2生成一张表
统计条件:在T2中查找所有“上课”事件的ID,同时对于某个ID在T2中有多个记录,】
取其abs(tCount-90)最小,同时tCount >=80 AND tCount <=90
如果某个ID在T2中没有记录或者某个ID在T2中有记录,但是在其tCount的值不在[80,100]间
的所有ID,tDltCount="-99";
分开两个表:
--定义要查询的数据条件
declare @tEvent varchar(10)
set @tEvent=上课
--第一个表(取其abs(tCount-90)最小,同时tCount >=80 AND tCount <=90)
select distinct *,newtCount=abs(tCount-90) from T2 a
where tID in(select tID from T1 where tEvent=@tEvent)
and tCount between 80 and 90
and abs(tCount-90)=(select min(abs(tCount-90)) from T2 where a.tID=tID)
--第二个表(在T2中没有记录或者在T2中有记录但是在tCount>=80 AND tCount<100时候没有记录)
select distinct a.tID,-99
from T1 a left join T2 b on a.tID=b.tID
where a.tEvent=@tEvent and b.tID is null or (
(b.tCount<80 or b.tCount>90)
and a.tID not in(select tID from t2 where tCount between 80 and 90))