SQL Query/Sub-query help needed
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?
select top (10) Serial, Max(DateTime)
from [Test].[dbo].[TestInfo]
where (TestedBy = 'JSMITH')
group by Serial
order by Max(DateTime) desc
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
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
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.
精彩评论