如何从具有多个id匹配的最大日期的行中选择值

时间:2013-06-27 21:51:43

标签: oracle

我不确定我的标题会提出我要求的问题。我正在使用SQL Developer来查询Oracle数据库。我已经构建了下面的查询,该查询能够为一个特定的ID提取我需要的值。我需要一个查询,它将拉出相同的值但多个ID。我需要每月运行相同的查询,以获得20-50个不同的ID。该数据库包含80,000多个ID,所以如果我能避免它,我不想拉动所有内容。这可能吗?

SELECT b.id, a.final_grade, a.final_score
FROM db.table1 a, db.table2 b
where a.survey_id=b.survey_id
and b.id = '1796'
and a.created_dt = (select max (a.created_dt) from db.table1 a, db.table2 b 
where a.survey_id=b.survey_id and b.cp_id = '1796')

非常感谢你的帮助

3 个答案:

答案 0 :(得分:2)

最简单的方法是使用ROW_NUMBER()和WITH子句。

with data as 
SELECT 
      b.id, 
      a.final_grade, 
       a.final_score,
       ROW_NUMBER OVER (PARTITION BY b.id, order by a.created_dt desc) rn
FROM 
        db.table1 a
        INNER JOIN  db.table2 b
        ON  a.survey_id=b.survey_id

where
 b.id in (<Comma seperated list of ids>)
)

SELECT * FROM DATA WHERE rn = 1

注意:如果给定id的created_dt存在联系,则将选择任意行。如果您希望显示关系,请将ROW_NUMBER替换为RANK()

答案 1 :(得分:0)

  SELECT b.id, a.final_grade, a.final_score
    FROM db.table1 a, db.table2 outerb
    where a.survey_id=outerb.survey_id
    and outerb.id IN (<SELECT query with your list of ids>)
    and a.created_dt = (select max (a.created_dt) from db.table1 a, db.table2 b 
    where a.survey_id=b.survey_id and b.cp_id = outerb.id )

这是你在找什么?问题不明确!

答案 2 :(得分:0)

我认为这就是你要找的东西,或者至少这是我对你的解释所得到的:

SELECT b.id, a.final_grade, a.final_score
    FROM db.table1 a, db.table2 b
    where a.survey_id=b.survey_id
    and b.id IN (<SELECT query with your list of ids>)
    and a.created_dt **IN** (select max (a.created_dt) from db.table1 a, db.table2 b 
    where a.survey_id=b.survey_id and b.cp_id = b.id )