SQL如何选择最新的日期项

时间:2010-11-03 19:20:25

标签: sql oracle select date

您好我有一个包含列的表:

*使用oracle

ID                  NUMBER
USER_ID            NUMBER
DATE_ADDED          DATE
DATE_VIEWED        DATE
DOCUMENT_ID        VARCHAR2
URL                VARCHAR2
DOCUMENT_TITLE      VARCHAR2
DOCUMENT_DATE        DATE

我想知道如何为给定用户获取最近添加的文档。

Select * FROM test_table WHERE user_id = value AND (do something with date_added column)

由于

6 个答案:

答案 0 :(得分:54)

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

答案 1 :(得分:13)

不确定确切的语法(使用varchar2类型,这意味着不是SQL Server因此TOP)但您可以使用LIMIT关键字来实现MySQL:

Select * FROM test_table WHERE user_id = value
     ORDER BY DATE_ADDED DESC LIMIT 1

Oracle中的rownum

 SELECT * FROM
     (Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)
 WHERE rnum = 1

如果是DB2,我不确定它是TOP,LIMIT还是rownum ......

答案 2 :(得分:7)

使用SQL Server尝试:

SELECT TOP 1 * FROM dbo.youTable WHERE user_id = 'userid' ORDER BY date_added desc

答案 3 :(得分:2)

假设您的RDBMS知道窗口函数,CTE和USER_ID是患者的id:

WITH TT AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY DOCUMENT_DATE DESC) AS N
    FROM test_table
)
SELECT *
FROM TT
WHERE N = 1;

我假设您想按DOCUMENT_DATE排序,如果需要,您可以轻松更改。如果你的RDBMS不知道窗口函数,你将不得不进行连接:

SELECT *
FROM test_table T1
INNER JOIN (SELECT USER_ID, MAX(DOCUMENT_DATE) AS maxDate
            FROM test_table
            GROUP BY USER_ID) T2
    ON T1.USER_ID = T2.USER_ID
        AND T1.DOCUMENT_DATE = T2.maxDate;

告诉我们你的RDBMS是多么好。此查询为每位患者选择最近的日期,您可以为给定患者添加条件。

答案 4 :(得分:2)

如果同时添加了多个文档,则您尚未指定查询应返回的内容,因此此查询假定您希望返回所有文档:

SELECT t.ID,
       t.USER_ID,
       t.DATE_ADDED,
       t.DATE_VIEWED,
       t.DOCUMENT_ID,
       t.URL,
       t.DOCUMENT_TITLE,
       t.DOCUMENT_DATE
FROM (
  SELECT test_table.*,
         RANK()
         OVER (ORDER BY DOCUMENT_DATE DESC) AS the_rank
  FROM   test_table
  WHERE  user_id = value
  )
WHERE the_rank = 1;

此查询只会传递一次数据。

答案 5 :(得分:0)

Select Top 1* FROM test_table WHERE user_id = value order by Date_Added Desc