+50
|
It is unclear to me what is a "more elegant way".
Oracle you can use the following statement to make columns to rows
select all_name from foo unpivot (all_name for col_name in ( his_name, her_name, other_name));
This is the syntax diagram of the select statement
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROMtable
Neither the
WHERE,GROUP BY, HAVING, LIMIT, SELECT, INTO, FOR UPDATE nor the LOCK IN SHARE MODE clause can increase the number of rows defined by the FROM clause. So if tableequals foo the query cannot contains more rows than the table foo.So MySQL does not have such an "elegant" way to unpivot a table.
A way to do such unpivoting without the use of UNION can be done buy using a join. We want to create 3 rows for each row of the
foo table, so we create an auxiliary table containing three rows and (cross) join it to the foo table. Now we have three rows in our query for each row in the base table foo. Each query row can be filled by the appropriate data. Instead the ELT function one can use IF or CASE.
MySQL 5.6 Schema Setup:
Pivot Query:
Of course there are different ways to create a table containing the three rows with values 1,2,3:
Using an auxiliarytable
:
Using an auxiliary table:
using a constant expression:
counting row numbers: I found it here
using one of the dictionary views:
|
Monday, 6 February 2017
Can I combine the results from multiple columns into a single column without UNION?
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment