从三个表的子查询中选择MAX值

时间:2014-05-07 19:10:18

标签: sql oracle subquery max union-all

我正在尝试选择SECTION,LAST_MDS_MON,DAYS_BETWEEN,其中LAST_MDS_MON对于不同的SECTION是MAX,来自下面的查询...请帮助!

SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
FROM MON_DIS_AC_REV
GROUP BY STATE_CODE,SHRP_ID
UNION ALL
SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
FROM MON_DIS_JPCC_REV
GROUP BY STATE_CODE,SHRP_ID
UNION ALL
SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
FROM MON_DIS_CRCP_REV
GROUP BY STATE_CODE,SHRP_ID

1 个答案:

答案 0 :(得分:0)

SELECT
  SECTION,
  LAST_MDS_MON,
  DAYS_BETWEEN
FROM
  (
  SELECT
    SECTION,
    LAST_MDS_MON,
    DAYS_BETWEEN,
    RANK() OVER (PARTITION BY SECTION ORDER BY LAST_MDS_MON desc) AS RANK
  FROM
    (
    SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
    FROM MON_DIS_AC_REV
    GROUP BY STATE_CODE,SHRP_ID
    UNION ALL
    SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
    FROM MON_DIS_JPCC_REV
    GROUP BY STATE_CODE,SHRP_ID
    UNION ALL
    SELECT STATE_CODE||SHRP_ID AS SECTION,MAX(SURVEY_DATE) AS LAST_MDS_MON,((ADD_MONTHS(CURRENT_DATE,18))-TO_DATE(MAX(SURVEY_DATE))) AS DAYS_BETWEEN
    FROM MON_DIS_CRCP_REV
    GROUP BY STATE_CODE,SHRP_ID
    )
  )
WHERE
  RANK = 1