开发者

SQL Picking Top Date out of the Date Field

So I have a table with a date column. I want to be able to group these dates by Item field of some type. For example I might have a column called Item and within the Item field there may be 500 entries. Item 12345 might have 5 entires, each with a price. I want to be able to pull out all of the Items, grouped by the newest date.

031126-2M1      开发者_如何学JAVA                    8/10/2011 12:00:00 AM   7.8678
031126-2M1                          7/22/2011 12:00:00 AM   9.5620
031126-2M1                          7/15/2011 12:00:00 AM   8.8090

In this example, I want to show the item with the closest date, 7/15/2011 so I can use that Price of 8.8090. The list would then show the other items, some may have one entry, others might have many, but I want to show all of them with the closets date. Need Help!

Thanks


A MS SQL Server version...

WITH
  sorted_data AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY item_id ORDER BY item_date DESC) AS row_id,
    *
  FROM
    item_data
  WHERE
    item_date <= getDate()
)

SELECT * FROM sorted_data WHERE row_id = 1


selct * from table where This = that Group by something having This. order by date desc.

having "THIS" should be in the query itself.

hope this helps..

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜