我知道MySQL有限制命令,但我不知道我应该在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
答案 0 :(得分:3)
limit命令在sql server中是最高的
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
每张海报的澄清 - 这甚至不是一个顶级/限制问题。这是一个简单的分组声明。
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
答案 1 :(得分:1)
这通常是使用windowing functions完成的(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
请参阅this blog post以获得对该技术的一些改进(以避免扫描不必要的行)。
答案 2 :(得分: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