Anji007
Anji007

Reputation: 133

Inserting the data from one table to another by grouping one column in Oracle

I have a table

Table:1

LEDGER      SOURCE    CATEGORY    ACCOUNT   DR          CR
-------    --------   ---------  --------  ------      -------
ABC          JS1       JE1         A1     123456.7      2345.6
ABC          JS1       JE2         A1     16.7          345.6
ABC          JS2       JE3         A1     13456.7       10
ABC          JS3       JE4         A2     1456.7        45.6
ABC          JS1       JE2         A2     16            345
ABC          JS3       JE5         A2     2456.7        2.6
ABC          JS1       JE1         A3     156.7         25.6    .........

I want to insert this data into another table(table 2) by Source and Category.

For example, I have two lines for source and category JS1, JE1 i.e., line no 1,7 in table 1 for the accounts A1, A3. But I want to insert this data into table2 with only one line as shown below

Table:2

LEDGER SOURCE  CATEGORY  DR_A1  CR_A1   DR_A2  CR_A2  DR_A3  CR_A3
------ ------  -------   ------ ------  -----  -----  -----  ----
ABC    JS1     JE1       1234.7  2345.6 0       0      156.7  5.6
ABC    JS1     JE2       16.7    345.6  16      345    0      0
ABC    JS2     JE3       1346.7  10     0       0      0      0
ABC    JS3     JE4       0       0      1456.7  45.6   0      0
ABC    JS3     JE5       0       0      2456.7  2.6    0      0 

(Note: Columns DR_A1, CR_A1 are DR of Account A1 and CR of A1 etc..)

Could anyone please help me to achieve this?

Upvotes: 0

Views: 69

Answers (2)

Radagast81
Radagast81

Reputation: 3016

If you're on Oracle 11g there is a standard way of doing this, that is even shorter:

SELECT *
  FROM tab
  pivot (MAX(dr) dr, MAX(cr) cr FOR (ACCOUNT) IN ('A1' AS a1, 'A2' as a2, 'A3' AS a3))

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521674

You can do this via a standard pivot query:

INSERT INTO Table2 (LEDGER, SOURCE, CATEGORY, DR_A1, CR_A1, DR_A2, CR_A2, DR_A3, CR_A3)
SELECT
    LEDGER,
    SOURCE,
    CATEGORY,
    MAX(CASE WHEN ACCOUNT = 'A1' THEN DR END) AS DR_A1,
    MAX(CASE WHEN ACCOUNT = 'A1' THEN CR END) AS CR_A1,
    MAX(CASE WHEN ACCOUNT = 'A2' THEN DR END) AS DR_A2,
    MAX(CASE WHEN ACCOUNT = 'A2' THEN CR END) AS CR_A2,
    MAX(CASE WHEN ACCOUNT = 'A3' THEN DR END) AS DR_A3,
    MAX(CASE WHEN ACCOUNT = 'A3' THEN CR END) AS CR_A3
FROM Table1
GROUP BY
    LEDGER,
    SOURCE,
    CATEGORY;

But looking at your expected output, it seems that maybe you are also adjusting the DR/CR values during the insert. If so, then you should add an explanation to your question about what is happening.

Upvotes: 1

Related Questions