1

我知道 MySQL 有 limit 命令,但我不知道我应该在 SQL Server 2008 中使用什么命令?

我需要选择 clientId 和每次取件的最后一天,大多数客户都有多个取件(取件表中有 65 000 + 条记录)。

select  P.ClientID,LastName+' '+FirsName as Name , Adress,p.PickupDate
from Pickup P,Clients C
where P.ClientID= C.ClientID
order by PickupDate desc limit 1


throwing error *Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'limit'.*
because **LIMIT** is not key word in SQL server
4

3 回答 3

3

限制命令在 sql server 中是 top

select top 1 P.ClientID
   ,LastName+' '+FirsName as Name 
   ,Adress
   ,p.PickupDate
from Pickup P
join Clients C on P.ClientID= C.ClientID
order by PickupDate desc 

根据海报的澄清 - 这甚至不是最高/限制问题。这是一个简单的 group by 语句。

select P.ClientID
   ,LastName+' '+FirsName as Name 
   ,Adress
   ,max(p.PickupDate)
from Pickup P
join Clients C on P.ClientID= C.ClientID
group by p.clientid, lastname + ' ' + firsname,adress
于 2013-02-25T04:50:09.720 回答
1

这通常使用窗口函数完成(2012 年之前) :

;WITH Data
AS
    (
    SELECT P.ClientID
        , LastName + ' ' + FirsName as Name
        , Address
        , PickupDate
        , ROW_NUMBER() OVER(PARTITION BY P.ClientID ORDER BY PickupDate DESC)
            AS [Entry #]
    FROM Pickup P
    JOIN Clients C
        ON P.ClientID= C.ClientID
    )
SELECT *
FROM Data
WHERE [Entry #] = 1
ORDER BY PickupDate DESC

有关该技术的一些很好的改进,请参阅此博客文章(以避免扫描不必要的行)。

于 2013-02-25T04:26:30.897 回答
1

尝试这个

select P.ClientID, LastName+' '+FirsName as 'Name', Adress, max(p.PickupDate)
from Pickup P,Clients C
where P.ClientID= C.ClientID
GROUP BY P.ClientID, Adress, LastName+' '+FirsName
order by PickupDate desc

小提琴

于 2013-02-25T04:27:09.547 回答