Calculate sum data and insert into another in SQL
I need to calculate sum of hours based on period column and insert into another table. Please see below example data. [code]
tbl_Summary
Client_id Store_id attribute1 Period Hours attributes
1 16 1 2/25/2007 1054.8 1
1 16 1 3/11/2007 1112.8 1
1 16 1 3/25/2007 1164.8 1
1 16 1 4/8/2007 1383.2 1
1 16 1 4/22/2007 1351.6 1
1 16 1 9/21/2008 1523.6 1**
1 16 1 10/5/2008 1020.26 1
1 16 1 10/19/2008 939.94 1
1 16 1 11/2/2008 903.14 1
1 16 1 8/9/2009 866.66 1
1 16 1 8/23/2009 915.48 1
1 16 1 9/6/2009 894.26 1
1 16 1 9/20/2009 1458.58 1[/b]
1 18 1 6/1/2008 1112.8 1
1 18 1 6/15/2008 1164.8 1
1 18 1 6/29/2008 1383.2 1 [b]
1 18 1 7/13/2008 1351.6 1
1 18 1 12/28/2008 1523.6 1
1 18 1 1/11/2009 979.2 1
1 18 1 1/25/2009 913.2 1
1 18 1 2/8/2009 930.6 1
1 18 1 2/22/2009 1143.4 1
1 18 1 5/31/2009 1066.16 1
1 18 1 6/14/2009 1174.8 1
1 18 1 6/28/2009 1099.2 1
1 18 1 7/12/2009 1014.5 1
Out put table will be like this.
tbl_history
--------------
[code]client_id store_id attribute1 hours attributes
1 16 1 8521.92 1
1 18 1 11196.92 1
Conditions for sp
Parameters to sp are only @client_id, @attribute1, @attributes
Find Max(Period) and go back to 52 weeks and calculate Sum(Hours) where Store_id= ? (in example 16 and 18 or each store_id) and client_id= @client_id and attribute1 = @attribute1 and attributes = @attributes. ie. Sum(Hours) will change based on store_id and when store_id will change period will change. See side moved data
store_id = 16 and period=9/20/2009 t开发者_如何学Goo 9/20/2009 sum(hours) =8521.92
- Insert into another table all output tbl_history.
Please give me solution. If you have any question ask me.
Thanks in advance
INSERT INTO tbl_history
SELECT client_id, store_id, attribute1, SUM(Hours), attributes
FROM tbl_Summary
WHERE PERIOD <=
(
SELECT MAX(PERIOD)
FROM tbl_Summary
WHERE client_id = @client_id
AND attribute1 = @attribute1
AND attributes = @attributes
)
AND PERIOD >=
(
SELECT (MAX(PERIOD) - 1 year) --(I dont remember the sintax for sql getdate() something but thats the idea)
FROM tbl_Summary
WHERE client_id = @client_id
AND attribute1 = @attribute1
AND attributes = @attributes
)
AND client_id = @client_id
AND attribute1 = @attribute1
AND attributes = @attributes
GROUP BY client_id, store_id, attribute1, attributes
Try it and tell me if it worked.
Regards.
精彩评论