2013-09-23 82 views
0

,所以我有這個表顯示記錄,即使不存在

Col1 Col2 Col3 
A  34  X 
B  43  L 
A  36  L 

現在,如果我查詢

select * from Table1 where col1 in ('A','B','C') 

我期待像

Col1 Col2 Col3 
A  34  X 
B  43  L 
A  36  L 
C  -  - 

是否有可能?

P.S:行C中的-只是表明列是空的。

+0

結果是什麼,當你試過了? – BWS

回答

1

您可以創建一個嵌套表架構的對象類型:

create type T_List1 as table of varchar2(100); 

,然後構造你的查詢,如下所示:

select s.column_value   as col1 
     , nvl(to_char(t.col2), '-') as col2 
     , nvl(col3, '-')   as col3 
    from Table1 t 
right join table(T_List1('A', 'B', 'C')) s 
    on (t.col1 = s.column_value) 

例子:

-- sample of data from your question 
with Table1(Col1, Col2, Col3) as(
    select 'A', 34, 'X' from dual union all 
    select 'B', 43, 'L' from dual union all 
    select 'A', 36, 'L' from dual 
) -- actual query 
select s.column_value   as col1 
     , nvl(to_char(t.col2), '-') as col2 
     , nvl(col3, '-')   as col3 
    from Table1 t 
    right join table(T_List1('A', 'B', 'C')) s --< here list your values 
    on (t.col1 = s.column_value)   -- as you would using `IN` clause 

結果:

COL1 COL2 COL3 
------------------------ 
A  36  L  
A  34  X  
B  43  L  
C  -  - 

SQLFiddle Demo

+2

額外的類型是不是真的有必要。你可以使用內建類型:'table(sys.odcivarchar2list('A','B','C','D'))' –

0

要做到這一點,你可以使用具有要在它即返回的所有值的驅動程序表:

col1 
A 
B 
C 
D 
E 

然後LEFT JOIN您的餐桌。

SELECT * 
FROM driver d 
LEFT JOIN Table1 t 
ON d.col1 = t.col1 
WHERE d.col1 in ('A','B','C') 
0

如果你不希望創建一個額外的嵌套表類型,如尼古拉斯克拉斯諾夫的回答或不想創建具有A,B,C行單獨的臨時表,則只需創建一個驅動表與with條款:

with driving_table(col) AS 
(
    select 'A' from dual 
    union 
    select 'B' from dual 
    union 
    select 'C' from dual 

) 
select dt.col   as col1 
    , nvl(to_char(t.col2), '-') as col2 
    , nvl(col3, '-')   as col3 
    from Table1 t 
right join driving_table dt 
    on (t.col1 = dt.col) 

http://sqlfiddle.com/#!4/112ef/2