SQL Inner join in a nested select statement

时间:2015-07-13 21:03:09

标签: sql oracle

I'm trying to do an inner join in a nested select statement. Basically, There are first and last reason IDs that produce a certain number (EX: 200). In another table, there are definitions for the IDs. I'm trying to pull the Last ID, along with the corresponding comment for whatever is pulled (EX: 200 - Patient Cancelled), then the first ID and the comment for whatever ID it is.

This is what I have so far:

Select BUSN_ID
    AREA_NAME
    DATE
    AREA_STATUS
(Select B.REASON_ID
      A.LAST_REASON_ID
      FROM BUSN_INFO A, BUSN_REASONS B
    WHERE A.LAST_REASON _ID=B.REASON_ID,
    (Select B.REASON_ID
          A. FIRST_REASON_ID
        FROM BUSN_INFO A, BUSN_REASONS B
        WHERE A_FIRST_REASON_ID = B.REASON_ID)
FROM BUSN_INFO 

I believe an inner join is best, but I'm stuck on how it would actually work.

Required result would look like (this is example dummy data):

First ID -- Busn Reason --       Last ID -- Busn Reason
1           Patient Sick          2          Patient Cancelled
2           Patient Cancelled     2          Patient Cancelled
3           Patient No Show       1          Patient Sick

Justin_Cave's SECOND example is the way I used to solve this problem.

1 个答案:

答案 0 :(得分:0)

如果要使用内联select语句,则内联select必须选择单个列,并且应该只返回到作为查询基础的表。在您发布的查询中,您多次选择相同的数字标识符。我的猜测是你真的想从查询表中查询一个字符串列 - 我会假设该列被称为reason_description

Select BUSN_ID,
       AREA_NAME,
       DATE,
       AREA_STATUS,
       a.last_reason_id,
       (Select B.REASON_description
          FROM BUSN_REASONS B
         WHERE A.LAST_REASON_ID=B.REASON_ID), 
       a.first_reason_id,
       (Select B.REASON_description
          FROM BUSN_REASONS B
         WHERE A.FIRST_REASON_ID = B.REASON_ID)
FROM BUSN_INFO A

更常规的是,您只需加入busn_reasons表两次

SELECT i.busn_id,
       i.area_name,
       i.date,
       i.area_status,
       i.last_reason_id,
       last_reason.reason_description,
       i.first_reason_id,
       first_reason.reason_description
  FROM busn_info i
       JOIN busn_reason first_reason
         ON( i.first_reason_id = first_reason.reason_id )
       JOIN busn_reason last_reason
         ON( i.last_reason_id = last_reason.reason_id )