首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql语句,取历史表上最新的价格和所在的日期

2012-01-19 
求一个sql语句,取历史表上最新的价格和所在的日期求一条sql语句有4个字段,名称,价格,日期,单位a1.207-6-12

求一个sql语句,取历史表上最新的价格和所在的日期
求一条sql语句  
有4个字段,名称,价格,   日期   ,单位
 
a   1.2   07-6-12   ,d
a   1.2   07-6-12   ,d
a   1.1   07-6-11,   a
b   3.5   07-6-10,   b

如何取到最新的价格和所在的日期和单位     ,如
a   1.2   07-6-12,d
b   3.5   07-6-10   ,b  

请注意,相同的日期,相同的名称只要一条就够了
谢谢!


[解决办法]
----方法1:
select * from table as a where not exists(select 1 from table where 名称=a.名称 and 日期 > a.日期)

----方法2:
select * from table as a where 日期=(select max(日期) from table where 名称=a.名称)
[解决办法]
create table #aa( 名称 varchar(5),价格 varchar(5),日期 datetime,单位 varchar(5))
insert into #aa
select 'a ', '1.2 ', '07-6-12 ' , 'd ' union all
select 'a ', '1.2 ', '07-6-12 ' , 'd ' union all
select 'a ', '1.1 ', '07-6-11 ' , 'a ' union all
select 'b ', '3.1 ', '07-6-10 ' , 'b '

select distinct * from #aa a where
not exists(select 1 from #aa b where a.名称=b.名称 and a.日期 <日期)

drop table #aa


(所影响的行数为 4 行)

名称 价格 日期 单位
----- ----- ------------------------------------------------------ -----
a 1.2 2007-06-12 00:00:00.000 d
b 3.1 2007-06-10 00:00:00.000 b

(所影响的行数为 2 行)
[解决办法]
select distinct * from 表 a (select 名称,max(日期) as 日期 from 表 group by 名称) b
where a.名称=b.名称 and a.日期=b.日期

热点排行