日期:2014-05-17  浏览次数:20532 次

问一个查询语句
名称   年份
A      2012
A      2010
A      1995
B      2011
B      1990
C      1999
C      1997
C      1995
C      1991


每个 名称 都有N条记录,属于不同的年份
我现在给出一个年份,如 1997

查询出每个 名称 距离1997最近的一条记录(小于该年份)
比如一个名称 下有   2012,1999,1995,那么该查出1995这条一。。

谢谢大家帮助
------最佳解决方案--------------------
SELECT *
FROM (select *,ROW_NUMBER()OVER(PARTITION BY 名称 order by abs(1997-年份),年份) AS Row from tab  )as a
WHERE row=1

------其他解决方案--------------------
说错了,是查出 【所有的名称】 最接近1997 这一条
------其他解决方案--------------------
SELECT * FROM TB T WHERE 年份=(select max(年份) from tb where 年份<1997 and 名称=t.名称)
and 年份<1997
------其他解决方案--------------------
select * from tab as a order by abs(1997-年份),年份
------其他解决方案--------------------
看看是否为4楼效果


------其他解决方案--------------------
----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-11-20 10:45:28
-- Version:
--      Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
-- Jul  9 2008 14:43:34 
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test]([名称] varchar(1),[年份] int)
insert [test]
select 'A',2012 union all
select 'A',2010 union all
select 'A',1995 union all
select 'B',2011 union all
select 'B',1990 union all
select 'C',1999 union all
select 'C',1997 union all
select 'C',1995 union all
select 'C',1991
go

declare @year int=2007
;with t
as(
select
*,
abs([年份]-@year) as Lens
from
test
where
[年份]<@year
)
select
[名称],
[年份]
from
t
where
Lens=(select min(Lens) from t a where a.名称=t.名称)
/*
名称   年份
---- -----------
A    1995
B    1990
C    1999

(3 行受影响)


*/


------其他解决方案--------------------
SELECT * FROM tb WHERE nianfen=(SELECT max(nianfen) FROM tb WHERE nianfen<1997)