SQL Server Select MAX

Posted on 2012-08-22
Last Modified: 2012-08-22
I have a table containing Serial Numbers many of which have multiple Ids:

Id   SerialNumbers
1     002561
2     002561
3     002569
4     002569
5     002569
6     005698
7     007120
8     007120

I need to write a SQL Server query to produce a new table containing just the serial number entries with the highest id's so that, in the above list, only rows with these Id's would be selected:   2, 5, 6 & 8.

I've tried various queries using MAX, GROUP BY & HAVING but I haven't come up with a solution.  What's the best way of doing this?
Question by:ccravenbartle
    LVL 25

    Assisted Solution

    Did you try
    SELECT max(Id) as Id, SerialNumbers
    FROM your_table
    GROUP BY SerialNumbers
    LVL 12

    Accepted Solution

    SELECT id , SerialNumbers
    FROM (SELECT id , SerialNumbers , row_number() OVER (PARTITION BY SerialNumbers ORDER BY id DESC) RowNo FROM YourTable) T
    WHERE T.RowNo = 1

    Open in new window

    LVL 142

    Expert Comment

    by:Guy Hengel [angelIII / a3]

    Expert Comment

    SELECT MAX(id) FROM #tbl GROUP BY SerialNumbers

    Open in new window

    LVL 8

    Expert Comment

    by:Anurag Agarwal
    SELECT MAX(id) id  from tbl
    group by serialnumbers
    LVL 9

    Expert Comment

    Select max(id) as ID from tablename group by SerialNumbers

    Author Closing Comment

    Thank you all for your responses.   Much appreciated.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Suggested Solutions

    Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
    This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
    Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now