根据另一个表在表中插入值

时间:2011-03-28 13:28:11

标签: sql sql-server-2005

我需要编写一个存储过程。 我有一个包含一些数据的表,现在我需要根据某些条件将相关数据插入到另一个表中

示例:

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

基于这个条件

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

请帮帮我

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您是否必须使用存储过程甚至是其他表?

查看服务器更好,因为它永远不会与真实数据同步。 (也没有真正的性能问题。)

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