在SQL中,我试图获取最新的记录(最小记录小于或等于传递的datetime
参数)
例如,在我的名为serviceentry
的表格中,有一个名为ServiceDateTime
如何在我的select子句中应用Max。因此,如果部件有服务条目,我想在下面根据我的日期时间参数
获取最大记录select
Part.System as Subsystem, Part.ID as PartNumber,
Part.PartDescription, System.SystemFullName,
COALESCE(ServiceEntryPart.PartRevisionNumber, Part.RevisionNumber) AS Revision
from
Part
left outer join
ServiceEntryPart on Part.ID = ServiceEntryPart.PartID
left outer join
ServiceEntry on ServiceEntryPart.ServiceEntryID = ServiceEntry.ID
left outer join
System on System.PlatformID = Part.platformid
where
part.id = 670220
and ServiceEntry.ServiceDateTime <= '1/1/2014'
答案 0 :(得分:3)
这就是诀窍:
select TOP 1 * from myTable where myDate <= @SomeDate order by se.ServiceDateTime desc
如果您需要所有最大值小于或等于给定参数的记录,请考虑以下内容,糟糕,但是得到了点,解决方案的示例:
示例:强>
CREATE TABLE Parts
(
id int auto_increment primary key,
part_name varchar(10),
buyer varchar(10)
);
CREATE TABLE Purchase
(
id int auto_increment primary key,
buyer varchar(10),
purchase_date datetime
);
INSERT INTO Parts (part_name, buyer)
VALUES ('hammer','mc'), ('wrench','larry'), ('screw','bill');
INSERT INTO Purchase (buyer, purchase_date)
VALUES ('mc','2012-01-01 22:00'), ('larry', '2014-01-01 22:00'), ('bill', '2012-01-01 22:00');
SET @my_date ='2013-01-01 22:00';
select pa.buyer as buyer , purchase_date, pa.part_name as part_name
from Parts pa
left outer join Purchase pu on (pa.buyer = pu.buyer)
inner join (
select max(purchase_date) max_date from Purchase where purchase_date <= @my_date) md
on md.max_date = pu.purchase_date
答案 1 :(得分:0)
我现在只使用PostgresSQL做了类似的事情 - 我选择了这种方式:(上下文:在过去一年的交易模拟器中,获取时间戳的资金管理书的ID,这是最新的交易日期之前的一个年交易模拟循环) 首先 ?将是一个股票代码,第二个是交易日期。对于MSSQL,您将在查询之前用set rowcount = 1替换限制1。
select mmgb_id from mmgr_book
where mmgb_shortname = ?
and mmgb_infodate <= ?
order by mmgb_infodate DESC
limit 1