Rows to columns SQL:
ORDER_MODE
|
ORDER_STATUS
|
ORDER_TOTAL
|
direct
|
0
|
100
|
direct
|
1
|
200
|
online
|
0
|
300
|
online
|
1
|
400
|
need to convert
like this:
Order_MODE
|
STAT_0
|
STAT_1
|
direct
|
100
|
200
|
online
|
300
|
400
|
Method 1:
SQL> SELECT
UPPER(o.order_mode) order_mode
,SUM(DECODE(o.order_status,
0, o.order_total)) stat_0
,SUM(DECODE(o.order_status,
1, o.order_total)) stat_1
FROM orders
o
GROUP BY o.order_mode
ORDER BY 1
Method 2:
SQL> SELECT UPPER(order_mode) , stat_0, stat_1
FROM (
SELECT o.order_mode,o.order_status
,SUM(o.order_total)
order_total
FROM orders o GROUP BY o.order_mode,
o.order_status
)
PIVOT ( SUM(order_total)
FOR order_status IN (0 stat_0, 1 stat_1) )
Columns to Rows:
COL_A COL_B COL_C
1 2 3
COL D
1
2
3
SELECT COL_A as COL_D from tbl
UNION ALL
SELECT COL_B as COL_D from tbl
UNION ALL
SELECT COL_C as COL_D from tbl;
with tt
2 as
3 (
4 select 1 cola, 2 colb, 3 colc, 4 cold from dual
5 )
-- End Of Data Part --
6 select cola
7 from tt
8 union all
9 select colb
10 from tt
11 union all
12 select colc
13 from tt
14 union all
15 select cold
16 from tt;
COLA
----------
1
2
3
4
OR another approach
SELECT * FROM unpivot_test;
ID CUSTOMER_ID PRODUCT_CODE_A PRODUCT_CODE_B PRODUCT_CODE_C PRODUCT_CODE_D
---------- ----------- -------------- -------------- -------------- --------------
1 101 10 20 30
2 102 40 50
3 103 60 70 80 90
4 104 100
4 rows selected.
SQL>
The UNPIVOT operator converts this column-based data into individual rows.
SELECT *
FROM unpivot_test
UNPIVOT INCLUDE NULLS (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B', product_code_c AS 'C', product_code_d AS 'D'));
ID CUSTOMER_ID P QUANTITY
---------- ----------- - ----------
1 101 A 10
1 101 B 20
1 101 C 30
1 101 D
2 102 A 40
2 102 B
2 102 C 50
2 102 D
3 103 A 60
3 103 B 70
3 103 C 80
3 103 D 90
4 104 A 100
4 104 B
4 104 C
4 104 D
SELECT * FROM unpivot_test;
ID CUSTOMER_ID PRODUCT_CODE_A PRODUCT_CODE_B PRODUCT_CODE_C PRODUCT_CODE_D
---------- ----------- -------------- -------------- -------------- --------------
1 101 10 20 30
2 102 40 50
3 103 60 70 80 90
4 104 100
4 rows selected.
SQL>
The UNPIVOT operator converts this column-based data into individual rows.
SELECT *
FROM unpivot_test
UNPIVOT INCLUDE NULLS (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B', product_code_c AS 'C', product_code_d AS 'D'));
ID CUSTOMER_ID P QUANTITY
---------- ----------- - ----------
1 101 A 10
1 101 B 20
1 101 C 30
1 101 D
2 102 A 40
2 102 B
2 102 C 50
2 102 D
3 103 A 60
3 103 B 70
3 103 C 80
3 103 D 90
4 104 A 100
4 104 B
4 104 C
4 104 D
No comments:
Post a Comment