请高手写sql语句

来源:百度知道 编辑:UC知道 时间:2024/06/03 18:24:57
+--------+-------+---------------+
| name | price | lasttime |
+--------+-------+---------------+
| Baidu | 800 | 1187399007507 |
| Baidu | 900 | 1211873911000 |
| Google | 1200 | 1211873990750 |
| eBay | 400 | 1211874026671 |
| Yahoo | 600 | 1211874122906 |
| Sina | 400 | 1211874137015 |
+--------+-------+---------------+

请写出name列值不重复,lasttime值最大的记录,结果如下所示:
+--------+-------+---------------+
| name | price | lasttime |
+--------+-------+---------------+
| Baidu | 900 | 1211873911000 |
| Google | 1200 | 1211873990750 |
| eBay | 400 | 1211874026671 |
| Yahoo | 600 | 1211874122906 |
| Sina | 400 | 1211874137015 |
+--------+-------+---------------+
已解决。select c.name,p.price from company c,price p where lasttime in (select max(lasttime) from price group by cid) and p.cid=c.cid; 分数大家共享吧。

创建自定义函数
CREATE function Fun_Price( @quarter Varchar(200) )
returns int
as
begin
declare @ltime datetime
declare @price int
select @ltime=max(LASTTIME) from 表名 where quarter = @quarter
select @price=price from 表名 where quarter=@quarter and LASTTIME=@ltime
return @price
end
在查询中使用
SELECT quarter,Fun_Price(quarter),MAX(LASTTIME) FROM 表名 GROUP BY quarter

看不懂什么意思呢,呵呵~~学习下!等待高人!

不重复NAME列可以用DISTINCT,LASTTIME最大可以用MAX(LASTTIME)

select name,price ,max(lasttime)
from tabname
group by name,price