0

I have a table that looks like this:

BARCODE      | PRICE  | STARTDATE
007023819815 | 159000 | 2008-11-17 00:00:00.000
007023819815 | 319000 | 2009-02-01 00:00:00.000

How can I select so I can get the result like this:

BARCODE      | PRICE  | STARTDATE
007023819815 | 319000 | 2009-02-01 00:00:00.000

select by using max date.

Thanks in advance.

4
  • 1
    Check this answer to a similar question changing revision into startdate: stackoverflow.com/questions/95866/select-max-in-group Commented May 17, 2010 at 6:16
  • @rah.deex: I have reformatted your question, please have a look at the new version to learn about formatting (stackoverflow.com/editing-help) Commented May 17, 2010 at 6:19
  • @Peter Lang: Thanks Mr. Peter.. I'm sory about it.. Commented May 17, 2010 at 6:21
  • @DavGarcia: Thx Mr.DavGarcia.. Commented May 17, 2010 at 6:28

2 Answers 2

2
SELECT TOP 1 barcode, price, startdate
FROM TableName
ORDER BY startdate DESC

Or if there can be more than one rows.

SELECT barcode, price, startdate
FROM TableName A
WHERE startdate = (SELECT max(startdate) FROM TableName B WHERE B.barcode = A.barcode)

UPDATE changed second query to view max values per barcode.

Sign up to request clarification or add additional context in comments.

1 Comment

This will only select rows with the maximum start date, not the maximum start date per barcode
1

An elegant way to do that is using the analytic function row_number:

SELECT  barcode, price, startdate
FROM    (
        SELECT  *
        ,  ROW_NUMBER() OVER (PARTITION BY barcode ORDER BY startdate DESC) as rn
        FROM    YourTable
        ) subquery
WHERE   rn = 1

If performance is an issue, check out some more complex options in this blog post.

1 Comment

I think, you are missing DESC next to ORDER BY startdate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.