select max(DELIVERY_TIMESTAMP) from DOCUMENTS;
将返回最新文件的交付时间.如何返回最新文档的其他列?例如,我想要DOC_NAME
最近交付的文档?
我不确定如何形成这个WHERE
条款.
你有几个选择
SELECT DOC_NAME FROM DOCUMENTS WHERE DELIVERY_TIMESTAMP IN ( SELECT MAX(DELIVERY_TIMESTAMP) FROM DOCUMENTS )
或者加入
SELECT DOC_NAME FROM DOCUMENTS INNER JOIN ( SELECT MAX(DELIVERY_TIMESTAMP) AS MAX_DELIVERY_TIMESTAMP FROM DOCUMENTS ) AS M ON M.MAX_DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP
如果时间戳中存在重复项,或者您的"最大"条件中需要多列,则会变得更复杂(因为MAX()
只有所有行的一列)
这是JOIN
选项是唯一可用的选项,因为这样的结构不可用(比如具有相同时间戳的多个订单):
SELECT DOC_NAME FROM DOCUMENTS WHERE (DELIVERY_TIMESTAMP, ORDERID) IN ( SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC )
你实际上需要做的事情:
SELECT DOC_NAME FROM DOCUMENTS INNER JOIN ( SELECT TOP 1 DELIVERY_TIMESTAMP, ORDERID FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC, ORDERID DESC ) AS M ON M.DELIVERY_TIMESTAMP = DOCUMENTS.DELIVERY_TIMESTAMP AND M.ORDERID = DOCUMENTS.ORDERID