'Pivot Multiple Columns in SQL
I want to pivot multiple columns like the table below:
Original Table:
ID ClientName RegDate Interest AMT Principal AMT
1 A 01-Sep-19 100.00 25000.00
1 A 02-Sep-19 200.00 55000.00
2 B 02-Sep-19 300.00 90000.00
2 B 02-Oct-19 400.00 10000.00
2 B 03-Oct-19 500.00 18000.00
Expected Result:
ID ClientName 01/09/2019_INT 01/09/2019_Principal 02/09/2019_INT 02/09/2019_Principal 02/10/2019_INT 02/10/2019_Principal 03/10/2019_INT 03/10/2019_Principal
1 A 100.00 25000.00 200.00 55000.00
2 B 300.00 90000.00 400.00 10000.00 500.00 18000.00
Solution 1:[1]
You can use Conditional aggregation as a generic case(as we don't know the DBMS) :
SELECT ID, ClientName,
MAX(CASE WHEN RegDate = '2019-09-01' THEN InterestAMT END) AS "2019-09-01_INT",
MAX(CASE WHEN RegDate = '2019-09-01' THEN PrincipalAMT END) AS "2019-09-01_Principal",
MAX(CASE WHEN RegDate = '2019-09-02' THEN InterestAMT END) AS "2019-09-02_INT",
MAX(CASE WHEN RegDate = '2019-09-02' THEN PrincipalAMT END) AS "2019-09-02_Principal",
MAX(CASE WHEN RegDate = '2019-09-03' THEN InterestAMT END) AS "2019-09-03_INT",
MAX(CASE WHEN RegDate = '2019-09-03' THEN PrincipalAMT END) AS "2019-09-03_Principal"
FROM t
GROUP BY ID, ClientName
PIVOT
clause might also be used for some DBMS. the date literals should be preceded by date
for Oracle such as date'2019-09-01'
instead of '2019-09-01'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |