通过MAX搜索SQL()

时间:2008-10-31 15:52:01

标签: sql

select max(DELIVERY_TIMESTAMP) from DOCUMENTS;将返回最新文档的发送时间。如何为最新文档返回其他列?例如,我想要DOC_NAME获取最近发布的文档吗?

我不确定如何形成WHERE条款。

5 个答案:

答案 0 :(得分:6)

您有几个选择

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

答案 1 :(得分:4)

SELECT
  DELIVERY_TIMESTAMP,
  OTHER_COLUMN
FROM
  DOCUMENTS
WHERE
  DELIVERY_TIMESTAMP = (SELECT MAX(DELIVERY_TIMESTAMP) FROM DOCUMENTS)

答案 2 :(得分:2)

在MSSQL中,以下内容也适用:

SELECT TOP 1 * FROM DOCUMENTS ORDER BY DELIVERY_TIMESTAMP DESC

答案 3 :(得分:2)

在某些版本的SQL(即MySQL)上,您可以这样做:

SELECT *
FROM DOCUMENTS
ORDER BY DELIVERY_TIMESTAMP DESC
LIMIT 1

答案 4 :(得分:1)

Select Max(DELIVERY_TIMESTAMP), 
       Doc_Name
From TableName
Group By Doc_Name

应该这样做,除非我错过了问题中的某些内容。