带有订单的表有另一个有仓位的表。我希望订单表显示,但只有最新的位置。下面是我想要显示的3行的图片。省略其余部分。
SELECT DispatchTable.ordernumber, DispatchTable.truck,
DispatchTable.driver, DispatchTable.actualpickup,
DispatchTable.actualdropoff, orders.pickupdateandtime,
orders.dropoffdateandtime, Truck002.lastposition,
Truck002.lastdateandtime
FROM DispatchTable
INNER JOIN orders ON DispatchTable.ordernumber = orders.id
INNER JOIN Truck002 ON DispatchTable.truck = Truck002.name
WHERE (orders.status = 'onRoute')
答案 0 :(得分:1)
假设您想要卡车name
的最新SELECT DispatchTable.ordernumber,
DispatchTable.truck,
DispatchTable.driver,
DispatchTable.actualpickup,
DispatchTable.actualdropoff,
orders.pickupdateandtime,
orders.dropoffdateandtime,
TruckLatest.lastposition,
TruckLatest.lastdateandtime
FROM DispatchTable
INNER JOIN orders ON DispatchTable.ordernumber = orders.id
INNER JOIN (SELECT name,
lastposition,
lastdateandtime
FROM Truck002 Truck1
WHERE lastdateandtime =
(SELECT MAX(lastdateandtime)
FROM Truck002 Truck2
WHERE Truck2.name = Truck1.name)) TruckLatest
ON DispatchTable.truck = TruckLatest.name
WHERE (orders.status = 'onRoute')
行,这应该有效:
strto*()
答案 1 :(得分:0)
如果我理解正确,您可以使用ROW_NUMBER()
获取卡车的最新记录:
SELECT dt.ordernumber, dt.truck,
dt.driver, dt.actualpickup,
dt.actualdropoff, o.pickupdateandtime,
o.dropoffdateandtime, t.lastposition,
t.lastdateandtime
FROM DispatchTable dt INNER JOIN
orders o
ON dt.ordernumber = o.id INNER JOIN
(SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY t.name ORDER BY t.lastdateandtime DESC) as seqnum
FROM Truck002 t
) t
ON dt.truck = t.name
WHERE o.status = 'onRoute' AND seqnum = 1;
答案 2 :(得分:0)
首先,您为什么使用Truck002
的{{1}}字段而不是name
字段作为id
的链接?与使用DispacthTable
(数字字段或比id
更短的字符串)相比,这被认为是一种效率较低的方式。
其次,你应该在你的问题中提到每个name
可以有很多Order
个,并且每个DispatchTable
可以有很多DispacthTable
&#39 ; s,否则很多人会首先假设它是Truck002
和DispatchTable
之间的另一种方式。
第三,请尝试......
Truck002
如果您有任何问题或意见,请随时发表评论。
进一步阅读
https://msdn.microsoft.com/en-us/library/bb177906(v=office.12).aspx(SELECT DispatchTable.ordernumber,
DispatchTable.truck,
DispatchTable.driver,
DispatchTable.actualpickup,
DispatchTable.actualdropoff,
orders.pickupdateandtime,
orders.dropoffdateandtime,
Truck002.lastposition,
Truck002.lastdateandtime
FROM DispatchTable
INNER JOIN orders ON DispatchTable.ordernumber = orders.id
INNER JOIN Truck002 ON DispatchTable.truck = Truck002.name
WHERE (orders.status = 'onRoute')
GROUP BY ordernumber
HAVING lastdateandtime = MAX( lastdateandtime )
)
https://www.w3schools.com/sql/sql_having.asp(HAVING
)
https://msdn.microsoft.com/en-us/library/bb177905(v=office.12).aspx(HAVING
)