简体   繁体   English

需要SQL查询/子查询帮助

[英]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: 我试图从SQL Server 2005上的测试信息表中获取最后10个序列号的列表。我尝试了以下操作:

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? 有没有办法使用查询或子查询来获取最后10个序列号而不重复的序列号?

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. 如果仅需要串行字段,则必须在查询中仅写入串行字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM