问题
So I have this table
Col1 Col2 Col3
A 34 X
B 43 L
A 36 L
Now if I query
select * from Table1 where col1 in ('A','B','C')
I am expecting something like
Col1 Col2 Col3
A 34 X
B 43 L
A 36 L
C - -
Is it possible ?
P.S: the - in row C are just to show that the column is empty.
回答1:
You could create a nested table schema object type:
create type T_List1 as table of varchar2(100);
And then construct your query as follows:
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)
Example:
-- 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
Result:
COL1 COL2 COL3
------------------------
A 36 L
A 34 X
B 43 L
C - -
SQLFiddle Demo
回答2:
To do this you can use a driver table that has all the values you want returned in it ie:
col1
A
B
C
D
E
Then LEFT JOIN to your table.
SELECT *
FROM driver d
LEFT JOIN Table1 t
ON d.col1 = t.col1
WHERE d.col1 in ('A','B','C')
回答3:
If you don't want to create an extra nested table type as in Nicholas Krasnov's answer or don't want to create a separate temporary table with A,B,C rows then just create a driving table with with clause:
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
来源:https://stackoverflow.com/questions/18967133/display-record-even-if-it-doesnt-exist