Recent PostsRecent Posts Popular TopicsPopular Topics
 Home Search Members Calendar Who's On

 how to calculate row1 - row2 - row3.... Rate Topic Display Mode Topic Options
Author
 Message
 Posted Thursday, December 6, 2012 2:25 AM
 SSC Journeyman Group: General Forum Members Last Login: Thursday, November 5, 2015 2:05 AM Points: 94, Visits: 101
 I have a table which has some n no of rows. The table has Key, value1, value2, value3, etc fields. Now i need to insert a row which should be derived from the existing rows.eg: below are the data in the tableKey Value1 Value2 Value3ky010 100 150 90ky020 150 200 10ky030 580 400 10ky040 160 100 10ky050 110 250 10ky060 190 280 10ky070 350 270 10I need to insert a row as belowky055 310 50 -10the Value1, 2 and 3 are derived from the rows ky030 - ky040 - ky050If it addition i can simply write SELECT 'ky055', SUM(Value1), SUM(Value2), SUM(Value3)FROM table_nameWHERE Key in (ky030,ky040,ky050)but i need to subtract the rows...Can anyone help me to find a query to generate the value
Post #1393384
 Posted Thursday, December 6, 2012 9:06 AM
 UDP Broadcaster Group: General Forum Members Last Login: Tuesday, August 16, 2016 3:59 PM Points: 1,487, Visits: 1,076
 Please read this.http://www.sqlservercentral.com/articles/Best+Practices/61537/Here is a query that will make THIS specific example work.It rely's on your Key column to be ordered correctly. If the order of your keys is guaranteed then fine, but I would seriously look at the design of this table and data storage strategy before worrying about creating these queries.`DECLARE @Table TABLE ([KEY] Varchar(10),Value1 INT, Value2 INT, Value3 INT)INSERT INTO @TableSELECT 'ky010', 100, 150, 90 UNION ALLSELECT 'ky020', 150, 200, 10 UNION ALLSELECT 'ky030', 580, 400, 10 UNION ALLSELECT 'ky040', 160, 100, 10 UNION ALLSELECT 'ky050', 110, 250, 10 UNION ALLSELECT 'ky060', 190, 280, 10 UNION ALLSELECT 'ky070', 350, 270, 10SELECT 'ky055', SUM(CASE WHEN ID =1 THEN Value1 ELSE Value1 * -1 END), SUM(CASE WHEN ID =1 THEN Value2 ELSE Value2 * -1 END), SUM(CASE WHEN ID =1 THEN Value3 ELSE Value3 * -1 END)FROM ( SELECT RANK() OVER(ORDER BY [Key]) AS id, [Key], Value1, Value2, Value3 FROM @table WHERE [Key] in ('ky030','ky040','ky050'))t`
Post #1393589
 Posted Sunday, December 9, 2012 9:39 PM
 SSC Journeyman Group: General Forum Members Last Login: Thursday, November 5, 2015 2:05 AM Points: 94, Visits: 101
 Thanks Ray,Its working...Also the article is nice once. I will follow that....
Post #1394443

 Permissions