I want to select a single column given as the union of the content in cols 1, 2, 3, 4 of the same table. Since SUBQUERY
and CONDITION
are complicated I have the feeling that this is the wrong way to go for it:
SELECT COL1 FROM SUBQUERY WHERE CONDITION
UNION
SELECT COL2 FROM SUBQUERY WHERE CONDITION
UNION
SELECT COL3 FROM SUBQUERY WHERE CONDITION
UNION
SELECT COL4 FROM SUBQUERY WHERE CONDITION
UNION
SELECT COL5 FROM SUBQUERY WHERE CONDITION
Since this query looks bad both performance-wise and from the point of view of good coding style, Is there a better syntax in Oracle?
P.S.
If only the following pseudo code were correct... it would be perfect:
SELECT COL1 UNION COL2 UNION COL3 UNION COL4
FROM
SUBQUERY WHERE CONDITION;
You can use UNPIVOT
:
select * from
(select 'a' col1, 'b' col2, 'c' col3, 'd' col4, 'e' col5 from dual)
unpivot (
united_columns for subquery_column in ("COL1", "COL2", "COL3", "COL4", "COL5"));
SUBQUERY_COLUMN UNITED_COLUMNS
--------------- --------------
COL1 a
COL2 b
COL3 c
COL4 d
COL5 e
Place your select * from subquery where condition
istead of
select 'a' col1, 'b' col2, 'c' col3, 'd' col4, 'e' col5 from dual
More information about UNPIVOT
to get the idea: http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With