1

I need to write a Stored Procedure. I have a table with some data now I need to insert relevant data into another table according to some condition

Example:

Table 1

Name     Class Math Physics English
Alok     V     60   50      45
Bobby    V     78   87      86
Chandini VI    56   76      56
Dolly    VII   87   56      66

Based on this condition

Insert Values into Table2 
If class =V  
(Table2.Physics=Select sum(Table1.Physics) from Table1 where Class like ‘V’
 Table2.Maths=0 and table2.English=0)

If class =VI  
(Table2.Maths=Select sum(Table1.Maths) from Table1 where Class like ‘VI’
 Table2.Physics=0 and table2.English=0)

If class =VI  
(Table2.English =Select sum(Table1.English) from Table1 where Class like ‘VII’
 Table2.Physics=0 and table2.Maths =0)
]

 

Table 2

Class Math Physics English
V     0    137     0
VI    56   0       0
VII   0    0       66

Kindly Help me out

1

2 Answers 2

3
INSERT
INTO    table2
SELECT  class,
        SUM(CASE WHEN class = 'V' THEN Physics ELSE 0 END),
        SUM(CASE WHEN class = 'VI' THEN Math ELSE 0 END),
        SUM(CASE WHEN class = 'VII' THEN English ELSE 0 END)
FROM    table1
GROUP BY
        class
Sign up to request clarification or add additional context in comments.

Comments

0

Do you have to use a stored procedure or even another table?

A view servers you better as it can never go off sync with the real data. (There is no real performance issue either.)

CREATE VIEW table2 AS
SELECT class,
       SUM(CASE WHEN table1.class = 'V' THEN table1.physics ELSE 0 END),
       SUM(CASE WHEN table1.class = 'VI' THEN table1.math ELSE 0 END),
       SUM(CASE WHEN table1.class = 'VII' THEN table1.english ELSE 0 END)
FROM table1
GROUP BY class

1 Comment

This is the same as @Quassnoi 's solution but with a view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.