我有一个表,其中包含多个位置之间的机器移动记录。
由于我只在列表中显示最新的数据,因此到目前为止,我在 sql 中只读取了每台机器具有最新记录日期的数据行。
Select *
From records
INNER JOIN
(Select max(processdate) as maxDate, machinetag, machineno
from records
group by machinetag, machineno ) as lrcd
on records.machineTag = lrcd.machineTag and records.machineno = lrcd.machineno
and records.processDate = lrcd.maxDate
我读了很多帖子,但没有找到任何解决方案。
如何使用 queryover 实现此场景?
提前非常感谢您。 萨沙
最佳答案
内连接几乎总是可以重写为 where 子句和投影的组合。
类似这样的东西(我在没有编译器的情况下编写,如果有任何错误,抱歉):
Select
records.*,
(select max(processdate) as maxdate
from records
where lrcd.machineno = records.machineno)
-- add more projections if you need them
From records
where records.processDate =
(select max(processdate) as maxDate
from records
where lrcd.machineno = records.machineno) as lrcd
现在使用 QueryOver 应该很容易实现(子查询可以在投影或限制中实现)。
不用担心重复的代码 - 查询计划会为您优化它。
关于NHibernate:将子查询(使用聚合)与表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25199964/