我写了一个查询,希望根据最新日期返回记录。
在这个特定的查询中,我使用了select top 1, order by desc
语句。但是我没有获得前1名,而是获得所有日期。
这是我的疑问:
SELECT Serial Number,
CustomerName,
CellphoneModel..........
FROM CustomersTable INNER JOIN CellPhoneTables
ON CustomersTable.CustomerID = CellphoneTable.CustomerID
INNER JOIN MaintainanceTable......
....... AND CellphoneTables.SerialNumber IN
(SELECT TOP(1) Serial Number
FROM CellPhoneTable
WHERE (CustomerID = CustomersTable.CustomerID)
ORDER BY MaintananceTable.CheckDate DESC)
这些是我的结果::
Serial Number Customers .............................. CheckedOnDate
11111 HomeCell 1/1/2012
11111 HomeCell 1/2/2012
11111 HomeCell 7/7/2012
22222 BarbsConnect 2/3/2012
22222 Barbsconnect 18/7/2012
这些是我想要的结果:
SerialNumber Customer CheckedOnDate
11111 HomeCell 7/72012
22222 BarbsConnect 18/7/2012
我在下面做了一个练习示例(哪个有效),所以我上面的例子可能做错了什么?
SELECT a.AuthorID, a.AuthorName, b.ISDN, b.BookTitle, b.NumberOfPages, b.DatePublished, b.Author
FROM Authors AS a LEFT OUTER JOIN
Books AS b ON a.AuthorID = b.Author AND b.ISDN IN
(SELECT TOP (1) ISDN
FROM Books
WHERE (Author = a.AuthorID)
ORDER BY DatePublished)
答案 0 :(得分:2)
对于给定的序列号,您有多个CheckDates,您应该选择最大日期来获取所需的记录而不是序列号。以下查询应该获取所需的记录:
select *
from CustomersTable CT inner join CellphoneTables CellTbl on CT.CustomerID = CellTbl.CustomerID
inner join MaintainanceTable MT on MT.CustomerID = CT.CustomerID
and MT.CheckDate in (SELECT TOP(1) CheckDate
FROM MaintainanceTable
WHERE (CustomerID = CT.CustomerID)
ORDER BY MT.CheckDate desc)