2017-01-05 48 views
0

我正在試驗不同的方法來實現下面的輸出。自己加入一個表格以給出沒有null的記錄

CON_ID Compartment AMOUNT  EXP_DT 
train  Compartment 1  100  '20-jan-2016' 

請查找下面使用的數據。

with src_t as 
(
select 'A' as miot_id,'Train' as Obj_id from dual 
union 
select 'B' as miot_id,'Candy' as obj_id from dual 
), 
eat as (
select 'Candy' as eat_id,'Compartment1' as compartment,'20-jan-2016' as exp_dt from dual 
union 
select 'Cookies' as eat_id,'Compartment2' as compartment,'20-feb-2016' as exp_dt from dual 
), 
miot_t as (
select 'A' as miot_id,'Compartment1' as vin from dual 
UNION 
select 'B' as miot_id,'Compartment2' as vin from dual 
), 
condition_t as (
select 'Train' as con_id,100 as amount from dual 
) 

我試過下面的查詢。

Select con_id,Compartment,amount 
     , exp_dt 
From src_t 
Left Join condition_t 
     On condition_t.con_id = src_t.obj_id 
Left Join eat 
     On eat.eat_id = src_t.obj_id 
Left Join miot_t 
     On miot_t.miot_id = src_t.miot_id; 

但它顯示爲空值。

CON_ID Compartment AMOUNT  EXP_DT 
    null Compartment 1  null  '20-jan-2016' 
Train  null   100   null 

我試過使用Max函數。這是做到這一點的一種方式,但是有沒有其他的方式呢..就像自我加入等等,所以它不會影響性能。感謝您的回答

這意味着車廂1列車有100個RS,關於'20 -JAN-2016'

回答

0

我有一種感覺,我做別人的功課他們過期的糖果,但在這裏它是。左連接表示始終包含左側表格(第一次提到)中的表格值,即使右側表格中沒有匹配的值。 NULL將被替換爲缺少的右表值。

對於你的情況,你只對匹配值感興趣,你對不匹配的值沒有興趣,所以你想要做一個內部連接,而不是外部連接('left join'是'left'外連接')。一個好的做法是始終從容器工作臺向內工作到容納的工作臺。這使得您的SQL更易於理解。這裏是我得到你想要的結果集的SQL:

WITH src_t 
    AS (SELECT 'A' AS miot_id, 'Train' AS obj_id 
      FROM DUAL 
     UNION 
     SELECT 'B' AS miot_id, 'Candy' AS obj_id 
      FROM DUAL) 
    , eat 
    AS (SELECT 'Candy' AS eat_id, 'Compartment1' AS compartment, '20-jan-2016' AS exp_dt 
      FROM DUAL 
     UNION 
     SELECT 'Cookies' AS eat_id, 'Compartment2' AS compartment, '20-feb-2016' AS exp_dt 
      FROM DUAL) 
    , miot_t 
    AS (SELECT 'A' AS miot_id, 'Compartment1' AS vin 
      FROM DUAL 
     UNION 
     SELECT 'B' AS miot_id, 'Compartment2' AS vin 
      FROM DUAL) 
    , condition_t 
    AS (SELECT 'Train' AS con_id, 100 AS amount 
      FROM DUAL) 
SELECT con_id 
    , compartment 
    , amount 
    , exp_dt 
    FROM condition_t 
     INNER JOIN src_t ON con_id = obj_id 
     INNER JOIN miot_t ON src_t.miot_id = miot_t.miot_id 
     INNER JOIN eat ON eat.compartment = miot_t.vin;