| Author |
Topic |
|
arkiboys
Master Smack Fu Yak Hacker
1433 Posts |
Posted - 2009-11-30 : 05:37:18
|
| /*The following data is in a table called tblMain.Looking at this table you see that I have grouped the data.The qoal is to update tblMain as follows:for each group, add a new record to the same table as follows: sum up the fx values, if the sign is positive use 3, if sign is negative use 4 The grouped records are also updated to show the ID of the new recorded added. See the RESULT section below.QUESTION: How is it possible to produce the RESULT in sql. I am trying to avoid using cursors.*/create table #tblMain(ID int primary key, IDCode varchar(20), Bcode int, pID tinyint, fx decimal(15, 2), Processed bit, ProcessedID int)insert into #tblMain (ID, IDCode, Bcode, pID, fx, Processed, ProcessedID)select 1, 'X', 937, 3, 638991.36, NULL, NULLunionselect 2, 'X',937,4,-853834.06, NULL, NULLunionselect 3,'X',937,4,-37847.78, NULL, NULLunionselect 4,'X',937,4,-6420.21, NULL, NULLunionselect 5,'D',759,4,-32582.23, NULL, NULLunionselect 6,'D',759,4,-21536.57, NULL, NULLunionselect 7,'W',671,4,-193898.53, NULL, NULLunionselect 8,'W',671,4,-66412.44, NULL, NULLunionselect 9,'Q',671,3,49833.14, NULL, NULLunionselect 10,'Q',671,4,-332.06, NULL, NULLselect * from #tblMaintruncate table #tblMain--RESULTinsert into #tblMain (ID, IDCode, Bcode, pID, fx, Processed, ProcessedID)select 1, 'X', 937, 3, 638991.36, 1, 50unionselect 2, 'X',937,4,-853834.06, 1, 50unionselect 3,'X',937,4,-37847.78, 1, 50unionselect 4,'X',937,4,-6420.21, 1, 50unionselect 5,'D',759,4,-32582.23, 1, 32unionselect 6,'D',759,4,-21536.57, 1, 32unionselect 7,'W',671,4,-193898.53, 1, 13unionselect 8,'W',671,4,-66412.44, 1, 13unionselect 9,'Q',671,3,49833.14, 1, 43unionselect 10,'Q',671,4,-332.06, 1, 43UNIONselect 50, 'X', 937, 4, -259110.69, 1, NULL --638991.36+(-853834.06)+(-37847.78)+(-6420.21)UNIONselect 32, 'D', 759, 4, -54118.80, 1, NULL ---32582.23+(-21536.57)UNIONselect 13, 'W', 671, 4, -260310.97, 1, NULL ---193898.53+(-66412.44)UNIONselect 43, 'Q', 671, 3, 49501.08, 1, NULL -- 49833.14+(-332.06)select * from #tblMaindrop table #tblMain |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-11-30 : 09:54:39
|
| [code]Insert into tableselect IDCode,case when sum(fx) > 0 then 3 else 4 end,sum(fx),1,NULL from tablegroup by IDCode[/code] |
 |
|
|
|
|
|