On how to pivot a table from vertical to horizontall orientation using SQL :
Method:
This technique is a bit more involved than the previous one, but it works equally well. The idea is to join the table to itself for as many columns as there are to produce horizontally:
INSERT INTO HORIZONTAL
(
YEAR ,
ACCOUNT_ID ,
NET_01 ,
NET_02 ,
NET_03 ,
NET_04 ,
NET_05 ,
NET_06 ,
NET_07 ,
NET_08 ,
NET_09 ,
NET_10 ,
NET_11 ,
NET_12 ,
)
SELECT
V01.YEAR ,
V01.ACCOUNT_ID ,
V01.NET_POSTING ,
IFNULL(V02.NET_POSTING , 0) ,
IFNULL(V03.NET_POSTING , 0) ,
IFNULL(V04.NET_POSTING , 0) ,
IFNULL(V05.NET_POSTING , 0) ,
IFNULL(V06.NET_POSTING , 0) ,
IFNULL(V07.NET_POSTING , 0) ,
IFNULL(V08.NET_POSTING , 0) ,
IFNULL(V09.NET_POSTING , 0) ,
IFNULL(V10.NET_POSTING , 0) ,
IFNULL(V11.NET_POSTING , 0) ,
IFNULL(V12.NET_POSTING , 0)
FROM VERTICAL V01
LEFT OUTER JOIN VERTICAL V02
on V01. YEAR = V02. YEAR
and V01. ACCOUNT_ID = V02. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V03
on V01. YEAR = V03. YEAR
and V01. ACCOUNT_ID = V03. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V04
on V01. YEAR = V04. YEAR
and V01. ACCOUNT_ID = V04. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V05
on V01. YEAR = V05. YEAR
and V01. ACCOUNT_ID = V05. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V06
on V01. YEAR = V06. YEAR
and V01. ACCOUNT_ID = V06. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V07
on V01. YEAR = V07. YEAR
and V01. ACCOUNT_ID = V07. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V08
on V01. YEAR = V08. YEAR
and V01. ACCOUNT_ID = V08. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V09
on V01. YEAR = V09.YEAR
and V01. ACCOUNT_ID = V09.ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V10
on V01. YEAR = V10.YEAR
and V01. ACCOUNT_ID = V10.ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V11
on V01. YEAR = V11. YEAR
and V01. ACCOUNT_ID = V11. ACCOUNT_ID
LEFT OUTER JOIN VERTICAL V12
on V01. YEAR = V12. YEAR
and V01. ACCOUNT_ID = V12. ACCOUNT_ID
WHERE V01.MONTH_VALUE = 01
and V02.MONTH_VALUE = 02
and V03.MONTH_VALUE = 03
and V04.MONTH_VALUE = 04
and V05.MONTH_VALUE = 05
and V06.MONTH_VALUE = 06
and V02.MONTH_VALUE = 07
and V03.MONTH_VALUE = 08
and V04.MONTH_VALUE = 09
and V05.MONTH_VALUE = 10
and V06.MONTH_VALUE = 11
and V06.MONTH_VALUE = 12
;
Go Back to the Top |