1

I am trying to get a list of the last 10 Serial numbers from a table of Test information on SQL Server 2005. I tried something like this:

SELECT DISTINCT TOP (10) Serial, DateTime
FROM [Test].[dbo].[TestInfo]
WHERE (TestedBy = 'JSMITH') ORDER BY DateTime DESC

which returns duplicate Serials:

+---------+-------------------------+
| Serial  | DateTime                |
+-----------------------------------+
| 1114048 | 2011-03-16 11:03:14.000 |
| 1617683 | 2011-03-11 15:07:29.000 |
| 1617683 | 2011-03-11 15:07:27.000 |
| 1617683 | 2011-03-11 15:07:26.000 |
| 1617683 | 2011-03-10 13:16:04.000 |
| 1617683 | 2011-03-10 13:15:35.000 |
| 1617683 | 2011-03-10 13:15:30.000 |
| 1617683 | 2011-03-07 13:42:48.000 |
| 1617683 | 2011-03-07 13:40:32.000 |
| 1617683 | 2011-03-07 13:37:58.000 |
+---------+-------------------------+

Is there a way, either using a query or sub-query to get the last 10 Serials without duplicates?

0

4 Answers 4

5
select top (10) Serial, Max(DateTime)
from [Test].[dbo].[TestInfo]
where (TestedBy = 'JSMITH')
group by Serial
order by Max(DateTime) desc
Sign up to request clarification or add additional context in comments.

1 Comment

I accepted your answer, but I removed the Max(DateTime) from the SELECT portion, since I really just need the list of Serials: SELECT TOP (10) Serial FROM [Test].[dbo].[TestInfo] WHERE (TestedBy = 'JSMITH') GROUP BY Serial ORDER BY Max(DateTime) DESC
1
SELECT TOP 10 
  * 
FROM (SELECT 
        Serial, 
        MAX(DateTime) AS DateTime
      FROM [Test].[dbo].[TestInfo]
      WHERE (TestedBy = 'JSMITH') 
      GROUP BY Serial) q1
ORDER BY q1.DateTime DESC

Comments

1

Probably something like:

SELECT DISTINCT TOP (10) Serial, DateTime
FROM (
  SELECT Serial, MAX(DateTime) AS DateTime
  FROM [Test].[dbo].[TestInfo]
  WHERE (TestedBy = 'JSMITH') 
  GROUP BY Serial
) AS sub
ORDER BY DateTime DESC

Comments

-1

it return duplicate rows beacuse the datetime is different for each row. if you need only the serial field you must write only Serial field in the query.

Comments

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.