E1 | E2 | E3 | EXPLANATION | AMOUNT |
---|---|---|---|---|
01 | PERSONNEL EXPENSES | 5000 | ||
01 | 1 | OFFICERS | 5000 | |
01 | 1 | 1 | BASIC SALARIES | 3000 |
01 | 1 | 2 | INCREASES AND COMPENSATION | 2000 |
02 | GOODS AND SERVICES PURCHASE EXPENSES | 8000 | ||
02 | 1 | SERVICE PROCUREMENT | 8000 | |
02 | 1 | 1 | STATIONERY PURCHASES | 6000 |
02 | 1 | 2 | OFFICE SUPPLIES PURCHASES | 2000 |
I want to obtain an output in the second table format using the table kept in the database as follows.
A1 | A2 | A3 | AMOUNT |
---|---|---|---|
PERSONNEL EXPENSES | 5000 | ||
PERSONNEL EXPENSES | OFFICERS | 5000 | |
PERSONNEL EXPENSES | OFFICERS | BASIC SALARIES | 3000 |
PERSONNEL EXPENSES | OFFICERS | INCREASES AND COMPENSATION | 2000 |
GOODS AND SERVICES PURCHASE EXPENSES | |||
GOODS AND SERVICES PURCHASE EXPENSES | SERVICE PROCUREMENT | 8000 | |
GOODS AND SERVICES PURCHASE EXPENSES | SERVICE PROCUREMENT | STATIONERY PURCHASES | 6000 |
GOODS AND SERVICES PURCHASE EXPENSES | SERVICE PROCUREMENT | OFFICE SUPPLIES PURCHASES | 2000 |
For this, I wrote a manual code in SQL as follows. But how can I make this more efficient?
SELECT
CASE WHEN E1 = '01' PERSONNEL EXPENSES'
WHEN E1 = '02' THEN 'GOODS AND SERVICES PURCHASE EXPENSES'
ELSE NULL END AS A1,
CASE WHEN E1 = '01' AND E2 = '1' THEN 'OFFICERS'
WHEN E1 = '02' AND E2 = '1' THEN 'SERVICE PROCUREMENT'
ELSE NULL END AS A2,
AMOUNT
FROM EXPENSES
How can I do this by taking from the column in the EXPENSES.EXPLANATION table without writing explanations like in this code?
2
Answers
Do you really use both PostgreSQL and Oracle? If so, I can’t help much about the former, but – for Oracle, here’s one option. Doesn’t look very pretty, though.
Sample data suggests that this is about some kind of a hierarchy:
Read comments within code; they explain what each CTE (and final SELECT) do:
Result:
If it is Oracle then you could use MODEL clause like below. It is fast and reliable.