0

我写了一个查询,希望它根据最新日期返回记录。

在这个特定的查询中,我使用了一个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)
4

1 回答 1

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)
于 2013-10-14T09:22:38.763 回答