如何在Oracle数据库中检索列的第一个值?

时间:2015-07-03 04:31:21

标签: sql oracle

我写了一个查询,下面我提到过。

    SELECT P.PERSON_ID,
                P.BIRTH_DATE,
                P.GENDER_CODE,
                LISTAGG(R.RACE_CODE, ',') WITHIN GROUP(ORDER BY R.RACE_CODE) AS RACE_CODE,
                P.HISPANIC_LATINO_CODE,
                C.CLINICALLY_DIAGNOSED_CODE,
                LISTAGG(C.CHARACTERISTIC_CODE, ',') WITHIN GROUP(ORDER BY C.CHARACTERISTIC_CODE) AS CHARA_CODES,
                P.PREV_ADOPTED_CODE,
                P.AGE_ADOPTED,
                PE.REMOVED_DATE
  FROM PERSON P
  LEFT OUTER JOIN RACE R
    ON P.PERSON_ID = R.PERSON_ID
  LEFT OUTER JOIN CHARACTERISTIC C
    ON C.PERSON_ID = P.PERSON_ID
  LEFT OUTER JOIN PLACEMENT_EPISODE PE
    ON P.PERSON_ID = PE.CHILD_ID
 GROUP BY P.PERSON_ID,
          P.BIRTH_DATE,
          P.GENDER_CODE,
          P.HISPANIC_LATINO_CODE,
          C.CLINICALLY_DIAGNOSED_CODE,
          P.PREV_ADOPTED_CODE,
          P.AGE_ADOPTED,
          PE.REMOVED_DATE

在这里,我想更改我的查询,以便它只检索pe.removed_date的第一个值。

我读到了FIRST()函数here。但是我无法更改查询以使用FIRST()函数。

假设PERSON表持有person_id的1,2,3 ......并且PLACEMENT_EPISODE包含如下值:

person_id   removed_date
   1          d1_1
   2          d2_1
   1          d1_2
   3          d3_1
   2          d2_2
   1          d1_3

所以我想:

 person_id           removed_date
  1            d1_1
  2            d2_1
  3            d3_1
来自PLACEMENT_EPISODE表的

child_id是来自PERSON表的外键引用主键person_id。

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER() OVER (PARTITION BY..按指定子句获取订单号。用select * from包装语句然后在其where子句中使用该命令编号,如此SQL:

select * from ( 
 SELECT         P.PERSON_ID,
                P.BIRTH_DATE,
                P.GENDER_CODE,
                LISTAGG(R.RACE_CODE, ',') WITHIN GROUP(ORDER BY R.RACE_CODE) AS RACE_CODE,
                P.HISPANIC_LATINO_CODE,
                C.CLINICALLY_DIAGNOSED_CODE,
                LISTAGG(C.CHARACTERISTIC_CODE, ',') WITHIN GROUP(ORDER BY C.CHARACTERISTIC_CODE) AS CHARA_CODES,
                P.PREV_ADOPTED_CODE,
                P.AGE_ADOPTED,
                PE.REMOVED_DATE,
                ROW_NUMBER() OVER (PARTITION BY P.PERSON_ID ORDER BY PE.REMOVED_DATE ASC) AS order_num
  FROM PERSON P
  LEFT OUTER JOIN RACE R
    ON P.PERSON_ID = R.PERSON_ID
  LEFT OUTER JOIN CHARACTERISTIC C
    ON C.PERSON_ID = P.PERSON_ID
  LEFT OUTER JOIN PLACEMENT_EPISODE PE
    ON P.PERSON_ID = PE.CHILD_ID
 GROUP BY P.PERSON_ID,
          P.BIRTH_DATE,
          P.GENDER_CODE,
          P.HISPANIC_LATINO_CODE,
          C.CLINICALLY_DIAGNOSED_CODE,
          P.PREV_ADOPTED_CODE,
          P.AGE_ADOPTED,
          PE.REMOVED_DATE
) WHERE order_num=1

答案 1 :(得分:0)

如果您只想要第一个选定的行,则可以使用rownum。

window