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

取得最新数据
某个表,有如下字段:
企业编号,年,月,评分

要求获得最新年月的所有企业的评分(最新那个)
也就是说,有2013和2012的数据就取2013的,有12月的和11月的就取12月的。
一个企业编号的数据只要一条,就是要最新的这条。
------最佳解决方案--------------------
select * from tb t where not exists (select 1 from tb where 企业编号=t.企业编号 and 年*100+月>t.年*100+t.月)

------其他解决方案--------------------
如果是2005,那
create table 企业表(企业编号 int,年 int,月 int,评分 int)
insert into 企业表
select 1,2011,3,81 union all
select 1,2012,6,82 union all
select 1,2013,8,83 union all
select 1,2012,12,84 union all
select 1,2011,4,86 union all
select 1,2015,7,87 union all
select 1,2014,6,88 union all
select 1,2013,2,89 union all
select 1,2015,3,90 union all
select 1,2012,9,91 union all
select 1,2011,12,92 union all
select 2,2014,6,88 union all
select 2,2013,2,89 union all
select 2,2015,3,90
go
select * from(
select *,row_number()over(partition by 企业编号 order by 年 desc,月 desc) as rn from 企业表
)t
where rn=1  
/*
企业编号        年           月           评分          rn
----------- ----------- ----------- ----------- --------------------
1           2015        7           87          1
2           2015        3           90          1

(2 行受影响)

*/
go
drop table 企业表

------其他解决方案--------------------
谁说我不在乎分的啊。
SELECT  *
 FROM    tb a
 WHERE   EXISTS ( SELECT 1
                  FROM   ( SELECT    MAX(年) 年 ,
                                     MAX(月) 月 ,
                                     企业编号
                           FROM      tb
                           GROUP BY  企业编号
                         ) b
 &