I have a question in regarding to Oracle Sql,
If I have a data called A, with 8 columns:
Spot| ID |Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday
-------------------------------------------------------------------------
A| 1 | 0.1 |0.15 | ...........................................
-------------------------------------------------------------------------
A| 2 | 0.2 |0.2 | ...........................................
-------------------------------------------------------------------------
A| 3 | 0.3 |0.25 | ...........................................
-------------------------------------------------------------------------
A| 4 | 0.4 |0.4 | ...........................................
-------------------------------------------------------------------------
Can I convert it to a table B like this:
Spot| Day of Week | ID | Value
-------------------------------------------------------------------------
A| 1 | 1 | 0.1
-------------------------------------------------------------------------
A| 1 | 2 | 0.2
-------------------------------------------------------------------------
A| 1 | 3 | 0.3
-------------------------------------------------------------------------
A| 1 | 4 | 0.4
-------------------------------------------------------------------------
A| 2 | 1 | 0.15
-------------------------------------------------------------------------
.......................................................................
Which is to combine columns (Sunday through Saturday) to a new column called 'Day of Week'
How can I do that please? Thanks!
You can use
UNPIVOT
:Oracle Setup:
Query:
Output:
There are essentially three ways to do this, each with their advantages and disadvantages. (There may be more than three, these are the ones I know.)
The first method uses
UNION ALL
and it is fine for small tables (performance is not important). It works in any version of Oracle. It goes something like this:It's inefficient, because the base table (A) is read seven times, one time for each branch of
UNION ALL
. Some rows may be cached, so perhaps it's not totally I/O time multiplied by seven, but it's still inefficient.Since Oracle 11.1 we have had
PIVOT
andUNPIVOT
. You need unpivoting, like this:This will work faster; it is not clear how Oracle implemented this under the hood, it may still do a
UNION ALL
, but a smart one - where the same row is used seven times, instead of being read repeatedly from disk. The disadvantage, of course, is that it is not available in older versions of Oracle.The third method uses a Cartesian join. It will work fast and it is available in all versions.
The subquery
h
in this solution may look fancy, but all it does is to create an inline viewh
with a single column,day_of_week
, with the values from 1 to 7. It can be created in any other way, this is just a fast (and common) one.