SQL - 根据日期

时间:2016-07-25 13:54:25

标签: sql oracle greatest-n-per-group

我正在尝试执行一个简单的代码,如下所示。

SELECT MR.ID_NUMBER
, MR.LAST_NAME
, MR.FIRST_NAME
, MR.EMAIL_ADDRESS
, MR.ASSIGNMENT_STATUS
, MR.assignment_start_Date
, AD.Address_line1
, AD.Town_Or_City



FROM Master_Rv MR
, Address_Details_v AD


WHERE Last_Name = 'Test'
and AD.Person_ID = MR.PERSON_ID

运行此代码时,会生成多行数据。我只想使用最新的Assignment_Start_Date'来检索数据。如果可能的话?我希望这是有道理的。

我做了我的研究,但似乎无法理解它,因此我在这里问过这个问题。非常感谢。

3 个答案:

答案 0 :(得分:2)

首先,学会使用正确的显式JOIN语法。简单的规则:从不FROM子句中使用逗号; 始终使用显式JOIN语法。

您问题的最简单答案是使用ROW_NUMBER()

SELECT MR.ID_NUMBER, MR.LAST_NAME, MR.FIRST_NAME,
       MR.EMAIL_ADDRESS, MR.ASSIGNMENT_STATUS, MR.assignment_start_Date,
       AD.Address_line1, AD.Town_Or_City
FROM Master_Rv MR JOIN
     (SELECT ad.*,
             ROW_NUMBER() OVER (PARTITION BY Person_ID ORDER BY Assignment_Start_Date DESC) as seqnum
      FROM Address_Details_v AD
     ) AD
     ON AD.Person_ID = MR.Person_ID
WHERE MR.Last_Name = 'Test' AND seqnum = 1;

答案 1 :(得分:0)

SELECT MR.ID_NUMBER
, MR.LAST_NAME
, MR.FIRST_NAME
, MR.EMAIL_ADDRESS
, MR.ASSIGNMENT_STATUS
, MR.assignment_start_Date
, AD.Address_line1
, AD.Town_Or_City



FROM Master_Rv MR
, Address_Details_v AD


WHERE Last_Name = 'Test'
and AD.Person_ID = MR.PERSON_ID
ORDER BY MR.assignment_start_Date DESC
LIMIT 10;

这会将您的记录订购到最新的assignment_start_Date,并将您的行数限制为10个最新数据, 但是你应该使用JOIN代替有效代码,而不是在" FROM"

答案 2 :(得分:0)

使用子选择,我们获得具有相同person_id的人的最大分配开始日期,然后用于仅获取此记录。

SELECT MR.ID_NUMBER
, MR.LAST_NAME
, MR.FIRST_NAME
, MR.EMAIL_ADDRESS
, MR.ASSIGNMENT_STATUS
, MR.assignment_start_Date
, AD.Address_line1
, AD.Town_Or_City
FROM Master_Rv MR
, Address_Details_v AD
WHERE mr.Last_Name = 'Test'
and MR.assignment_start_Date = (select max(assignment_start_Date) from Master_Rv where person_id=mr.person_id)   
and AD.Person_ID = MR.PERSON_ID