create table #temp(
[name] varchar(10),
[sl] int,
[rq] datetime,
[id] int IDENTITY (1, 1) NOT NULL)
insert into #temp(name,sl,rq) values('a',1,'2013-01-02')
insert into #temp(name,sl,rq) values('a',2,'2013-01-03')
insert into #temp(name,sl,rq) values('a',3,'2013-01-01')
insert into #temp(name,sl,rq) values('a',-2,'2013-01-02')
insert into #temp(name,sl,rq) values('a',-4,'2013-01-01')
insert into #temp(name,sl,rq) values('a',0,'2013-01-05')
insert into #temp(name,sl,rq) values('b',11,'2013-01-05')
insert into #temp(name,sl,rq) values('b',21,'2013-01-07')
insert into #temp(name,sl,rq) values('b',12,'2013-01-02')
insert into #temp(name,sl,rq) values('b',21,'2013-01-02')
insert into #temp(name,sl,rq) values('b',12,'2013-01-12')
insert into #temp(name,sl,rq) values('b',13,'2013-01-22')
insert into #temp(name,sl,rq) values('b',0,'2013-01-12')
insert into #temp(name,sl,rq) values('C',-10,'2013-01-05')
insert into #temp(name,sl,rq) values('C',21,'2013-01-07')
insert into #temp(name,sl,rq) values('C',12,'2013-01-02')
insert into #temp(name,sl,rq) values('C',-21,'2013-01-02')
insert into #temp(name,sl,rq) values('C',12,'2013-01-12')
insert into #temp(name,sl,rq) values('C',13,'2013-01-22')
insert into #temp(name,sl,rq) values('C',0,'2013-01-12')
--要求:
name sl rq id
a -4 2013-01-01 00:00:00.000 5
b 13 2013-01-22 00:00:00.000 12
C -21 2013-01-02 00:00:00.000 17
C 13 2013-01-22 00:00:00.000 19
/*说明:
SL为负数的:显示RQ最小的那个.
SL为正数的:显示RQ最大的那个.
我用union可以实现,想请问一下各位高手不用union如何实现?
先谢过.............
*/
------解决方案--------------------
只有两种情况的话我觉得union挺好的
------解决方案--------------------
用union 确实比较直观,容易立即诶
------解决方案--------------------
楼主贴的结果是否有误??
以下是返回绝对值最大值的ID记录
SELECT *
FROM #temp AS a
WHERE NOT EXISTS(SELECT 1 FROM #temp WHERE [name]=a.[name] AND (ABS(sl)>ABS(a.sl) OR (ABS(sl)=ABS(a.sl) AND id>a.id)))
/*
name sl rq id
a -4 2013-01-01 00:00:00.000 5
b 21 2013-01-02 00:00:00.000 10
C -21 2013-01-02 00:00:00.000 17
*/
------解决方案--------------------
每一个Name只显示一条数据?
select *
from #temp as a
where exists(select 1 from #temp where [name]=a.[name] having isnull(min(case when sign(sl)=-1 then [sl] end),max(case when sign([sl])!=-1 then [sl] end))=a.sl)
and not exists(select 1 from #temp where [name]=a.[name] and (sl=a.sl and rq>a.rq))
/*
name sl rq id
a -4 2013-01-01 00:00:00.000 5
b 21 2013-01-07 00:00:00.000 8
C -21 2013-01-02 00:00:00.000 17
*/