1

我有以下选择查询,它返回以下数据:

询问:

SELECT DISTINCT ALLVW.GP_PAYGROUP,
                ALLVW.PRD_END_DT,
                TMP.PRD_END_DT
FROM PS_AZ_DFN_ALPRD_VW ALLVW,
     PS_AZ_DFMPRP_TMP4 TMP
WHERE ALLVW.GP_PAYGROUP = TMP.GP_PAYGROUP
  AND ALLVW.PRD_END_DT < TMP.PRD_END_DT

结果:

PAYGROUP    PRD_END_DT      PRD_END_DT_1

AMZ_PG_T1   31-JAN-12   31-DEC-12
AMZ_PG_T1   29-FEB-12   31-DEC-12
AMZ_PG_T1   31-MAR-12   31-DEC-12
AMZ_PG_T1   30-NOV-12   31-DEC-12
AMZ_PG_T2   31-JAN-12   31-OCT-12
AMZ_PG_T2   30-SEP-12   31-OCT-12
AMZ_PG_T2   31-MAR-12   31-OCT-12
AMZ_PG_T2   30-APR-12   31-OCT-12

所以现在,我想要PRD_END_DTfor eachPAYGROUP之前的“x”个周期PRD_END_DT_1,例如 x = 1,我的查询应该返回:

 PAYGROUP    PRD_END_DT      PRD_END_DT_1
 AMZ_PG_T1   30-NOV-12       31-DEC-12
 AMZ_PG_T2   30-SEP-12       31-OCT-12

我厌倦了以下操作,但无济于事:

SELECT DISTINCT ALLVW.GP_PAYGROUP,
                ALLVW.PRD_END_DT,
                TMP.PRD_END_DT
FROM PS_AZ_DFN_ALPRD_VW ALLVW,
     PS_AZ_DFMPRP_TMP4 TMP
WHERE ALLVW.GP_PAYGROUP = TMP.GP_PAYGROUP
  AND ALLVW.PRD_END_DT < TMP.PRD_END_DT
  AND 1 =
    (SELECT COUNT(XVW.PRD_END_DT)
     FROM PS_AZ_DFN_ALPRD_VW XVW
     WHERE XVW.GP_PAYGROUP = TMP.GP_PAYGROUP
       AND XVW.PRD_END_DT < TMP.PRD_END_DT)

你能建议可能的方法吗?感谢您的投入。

4

3 回答 3

0

试用和使用dense_rank功能:

例如

Select a, b, c
From ( select a, b, c, dense_rank() over (partition by a order by b desc) r
       from table)
Where r < :x
于 2013-02-15T07:15:07.880 回答
0
SELECT * FROM (
  your original SELECT DISTINCT... query
) t where datediff(month, PRD_END_DT, PRD_END_DT_1) = x
于 2013-02-14T16:40:14.787 回答
0
SELECT DISTINCT ALLVW.GP_PAYGROUP, ALLVW.PRD_END_DT, TMP.PRD_END_DT
FROM PS_AZ_DFN_ALPRD_VW ALLVW
JOIN PS_AZ_DFMPRP_TMP4 TMP ON ALLVW.GP_PAYGROUP = TMP.GP_PAYGROUP
WHERE ALLVW.PRD_END_DT < TMP.PRD_END_DT
  AND add_months(trunc(ALLVW.PRD_END_DT, 'month'), 1) >= trunc(TMP.PRD_END_DT, 'month')
于 2013-02-14T16:40:37.190 回答