跪求sql语句

来源:百度知道 编辑:UC知道 时间:2024/05/18 23:12:04
一个表中有这样几个字段:
itemname price docdate
B 8.0 2007-07-05 00:00:00.000
A 2.0 2007-07-06 00:00:00.000
B 6.0 2007-07-21 00:00:00.000
A 3.0 2007-07-25 00:00:00.000
C 4.0 2007-07-29 00:00:00.000
我想通过一个sql语句取得每个物料最后一个时间的价格,
结果就是
C 4.0
A 3.0
B 6.0

假设表的名字叫test
SELECT itemname,
(SELECT price
FROM test
WHERE docdate = b.docdate) AS price
FROM (SELECT MAX(docdate) AS docdate, itemname
FROM test
GROUP BY itemname) b

再给您一个答案:
select itemname,price=(select top 1 price from tablename as a where itemname=tablename.itemname order by docdate)
from tablename

SELECT itemname,price FROM table where docdate in(
SELECT max(docdate) as 最后日期
FROM table
GROUP BY itemname
)

表名假定为table
测试通过!

用时间排序纪录,用itemname作为来源,读区 top 1 price

SELECT top 1 FROM 表 WHERE itemname='A' ORDER BY docdate DESC;

假设表的名字叫table1
select temname,price from table1 where docdate=(select max(docdate) from table1)

应该可以