连接两个具有最大值的表

时间:2018-03-09 11:18:32

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

想象一下,我有两张桌子:

使用:

JOBS
====
NAMEJOB
A
B
C
D
D
E

versions
========
NAMEJOB    CREATION_DATE       VERSION     CURR_VER
A          20180301            2            N
A          20180307            1            Y
B          20180302            3            N
B          20180304            2            N
C          20180308            1            Y

我想知道表JOBS的最大(版本)的所有创建日期:

RESULT:
NAMEJOB    CREATION_DATE       VERSION
A          20180301            2
B          20180302            3

我试图加入但不是作品(只给我看三行)。

select max(version) as maximo, curr_ver, creation_date, a.namejob  
from versions a, jobs b
where a.namejob=b.namejob
group by curr_ver,creation_date, a.namejob
having 
max(version) in (select max(version) as global_max from versions a, jobs b
where a.namejob=b.namejob);

你能帮我吗?

3 个答案:

答案 0 :(得分:0)

这是解决方案:

   SELECT A.NAMEJOB,CREATION_DATE,VERSION
FROM VERSIONS B
INNER JOIN ( SELECT  V.NAMEJOB ,MAX(VERSION) AS MAXIMO
             FROM VERSIONS V
             WHERE CURR_VER!='Y' GROUP BY V.NAMEJOB ) AS A
ON A.NAMEJOB = B.NAMEJOB and A.MAXIMO=B.version

FOR演示请点击链接:

  

http://sqlfiddle.com/#!17/6a2f6/5

答案 1 :(得分:0)

更简单的版本

select namejob, creation_date, max(version) 
from versions
group by namejob

如果你只想包含current_ver ='N'(不确定我明白为什么)

select namejob, creation_date, max(version) 
from versions
where curr_ver = 'N'
group by namejob

答案 2 :(得分:0)

目前尚不清楚为什么要加入表JOBS。仅使用versionsKEEP ( DENSE_RANK FIRST )表的查询应该有效,因为它似乎来自您想要的输出。

SELECT NAMEJOB,
         MIN (CREATION_DATE) KEEP (DENSE_RANK FIRST ORDER BY VERSION DESC)
            AS CREATION_DATE,
         MAX (VERSION) AS Version
    FROM versions
   WHERE CURR_VER = 'N'                                           -- required?
GROUP BY NAMEJOB;

或使用row_number()

SELECT NAMEJOB, CREATION_DATE, VERSION
  FROM (SELECT v.*,
               ROW_NUMBER ()
                  OVER (PARTITION BY NAMEJOB ORDER BY VERSION DESC)
                  rn
          FROM versions v
         WHERE CURR_VER = 'N') t
 WHERE rn = 1;