我正在尝试从SQL Server 2005上的测试信息表中获取最近10个序列号的列表。我尝试过这样的事情:
SELECT DISTINCT TOP (10) Serial, DateTime
FROM [Test].[dbo].[TestInfo]
WHERE (TestedBy = 'JSMITH') ORDER BY DateTime DESC
返回重复的序列号:
+---------+-------------------------+
| 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 |
+---------+-------------------------+
有没有办法,使用查询或子查询来获取最后10个没有重复的序列?
答案 0 :(得分:5)
select top (10) Serial, Max(DateTime)
from [Test].[dbo].[TestInfo]
where (TestedBy = 'JSMITH')
group by Serial
order by Max(DateTime) desc
答案 1 :(得分: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
答案 2 :(得分:1)
可能类似于:
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
答案 3 :(得分:-1)
它返回重复的行,因为每行的日期时间不同。 如果只需要序列字段,则必须在查询中只写入串行字段。