Question : Return Null when No Records Returned

All,

I need to some help building a sql script using the tables in the attachment.  Basically I need to return a value from tableB where MAX(tableB.date) < tableA.date.

See below for more details.

Thanks in advance.!



table A
ID    VAL  DATE
           
ID1   ABC  8/25/2010
ID2   EFG  8/25/2010
ID3   HIJ  8/25/2010

table B
ID   VAL1 VAL2 DATE

ID1  GRP1  1   7/25/2010
ID1  GRP2  2   6/25/2010
ID1  GRP2  3   5/25/2010
ID2  GRP1  1   7/25/2010

SELECT
  SUBQ.VAL,
  SUBQ.VAL1,
  SUBQ.VAL2,
  SUBQ.DATE
FROM
    (SELECT
       TABLE_A.VAL AS VAL,
       TABLE_B.VAL1 AS VAL1,
       TABLE_B.VAL2 AS VAL2,
       TABLE_B.DATE AS DATE
    FROM
       TABLE_B RIGHT OUTER JOIN TABLE_A ON TABLE_B.ID = TABLE_A.ID
    WHERE TABLE_A.VAL = 'ABC'
    AND TABLE_B.VAL1 = 'GRP2'
    AND TABLE_B.DATE < TABLE_A.DATE
    ORDER BY
      TABLE_B.DATE.DESC)SUBQ
WHERE
ROWNUM=1

This return  .. as it should

VAL          VAL1                    READINESS_VAL          DATE
------------- ---------------------- ---------------------- ----------------------
ABC           GRP2                       2                           6/25/2010

Problem is I would like to return the parameter values when no records are returned.
Thus substituting
    WHERE TABLE_A.VAL = 'EFG'
    AND TABLE_B.VAL1 = 'GRP2'

I would like to return

VAL          VAL1                    READINESS_VAL          DATE
------------- ---------------------- ---------------------- ----------------------
EFG           GRP2                      null                          null

rather than No Records.
Similary substituting
    WHERE TABLE_A.VAL = 'HIJ'
    AND TABLE_B.VAL1 = 'GRP1'

I would like to return

VAL          VAL1                    READINESS_VAL          DATE
------------- ---------------------- ---------------------- ----------------------
HIJ          GRP1                    null                   null

Answer : Return Null when No Records Returned

it cannot display the parameter value for the TABLE_B.VAL1 AS VAL1 in your query because we are doing a outer join on table_A and hence it can only get values for those columns which are found in table_A.

SELECT
  SUBQ.VAL,
  nvl(SUBQ.VAL1,'GRP2'), --> hard code your parameter value here so that it can return.
  SUBQ.VAL2,
  SUBQ.DATE_b,
  date_a
FROM
    (SELECT
       TABLE_A.VAL AS VAL,
       TABLE_B.VAL1 AS VAL1,
       TABLE_B.VAL2 AS VAL2,
       TABLE_B.DATE_b AS DATE_b,
       table_a.date_a as date_a
    FROM
       TABLE_B RIGHT OUTER JOIN TABLE_A ON TABLE_B.ID = TABLE_A.ID
     AND TABLE_A.VAL = 'ABC'
    AND TABLE_B.VAL1 = 'GRP2' --> this is another place the parameter value needs to be changed.
    AND TABLE_B.DATE_b < TABLE_A.DATE_a    
    ORDER BY
      TABLE_B.DATE_b DESC)SUBQ;

i am not sure but you can try with FULL OUTER JOIN if you want the column values from table_B as well to appear there.

Thanks
Random Solutions  
 
programming4us programming4us