分析函数Max和嵌套的case表达式

时间:2018-02-07 17:43:35

标签: sql oracle max

*编辑   我有以下输出表

      SELECT *

       ,CASE 
        WHEN AS_DT < START_DT AND MAX_ROLE = 'RED' AND MAX_PC_ID IS NOT NULL THEN START_DT
        WHEN A_DT BETWEEN START_DT AND NVL(END_DT,SYSDATE) AND ROLE = 'RED' AND PC_ID IS NOT NULL 
        THEN MIN(AS_DT) OVER (PARTITION BY CL_ID ORDER BY CL_ID ,AS_DT)
        ELSE ADD_MONTHS(SYSDATE,200) --TESTING PURPOSES
        END FIRST_ASSGN_DT

       FROM TABLEA

查询:

FIRST_AS_DT
10/7/2034
10/7/2034
6/16/14  
10/7/2034

输出:

<svg class="shape" width="100%" height="100vh" preserveAspectRatio="none" viewBox="0 0 1440 800" xmlns:pathdata="http://www.codrops.com/">

    <!-- background-image: 
      linear-gradient(-180deg,  rgba(black,0.69) 0%,  rgba(black,0.69) 100%),
      linear-gradient(-180deg,  rgba(black,0.100) 0%,  rgba(black,0.100) 100%),
      linear-gradient(-180deg,  rgba(black,0.49) 0%,  rgba(black,0.49) 100%);
    background-blend-mode: luminosity, lighten, saturation; -->

    <defs>
        <filter id="f1" x="0%" y="0%" width="100%" height="100%" primitiveUnits="objectBoundingBox">
            <feFlood x="0%" y="0%" width="60%" height="100%" flood-color="black" flood-opacity="0.69" result="lumiFill"/>
            <feBlend in="SourceGraphic" in2="lumiFill" mode="luminosity" result="lumiBlend"/>
            <feFlood x="40%" y="0%" width="60%" height="100%" flood-color="black" flood-opacity="0.1" result="lightenFill"/>
            <feBlend in="lumiBlend" in2="lightenFill" mode="lighten" result="lightenBlend"/>
            <feFlood x="0%" y="0%" width="100%" height="50%" flood-color="black" flood-opacity="0.49" result="saturationFill"/>
            <feBlend in="lightenBlend" in2="saturationFill" mode="saturation" result="saturationBlend"/>
        </filter>
    </defs>
    <rect x="50px" y="50px" width="300px" height="100px" fill="red" filter="url(#f1)" />
</svg>

期待结果不是6/16/14但是2/1/18,因为开始日期和结束日期之间的最短日期

思想?

1 个答案:

答案 0 :(得分:1)

尝试KEEP DENSE RANK FIRST / LAST个功能。

SELECT Id , clt_ID  ,  start_dt   , End_dt,
       max( a_date ) 
            KEEP (DENSE_RANK LAST ORDER BY 
                  case when ROLE = 'RED' AND a_date < start_dt then a_date end ) 
       As last_a_date_before_Start_dt,
       max(  userid  ) 
            KEEP (DENSE_RANK LAST ORDER BY 
                  case when ROLE = 'RED' AND a_date < start_dt then a_date end ) 
       As USERID
FROM table1
GROUP BY Id,  clt_ID  ,  start_dt  ,  End_dt

演示:http://sqlfiddle.com/#!4/2dbbb/13

| ID | CLT_ID |              START_DT |                END_DT | LAST_A_DATE_BEFORE_START_DT | USERID |
|----|--------|-----------------------|-----------------------|-----------------------------|--------|
|  1 |    101 | 2017-01-01 00:00:00.0 | 2017-02-01 00:00:00.0 |       2017-12-30 00:00:00.0 |    525 |