Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A stored procedure to sum on the third count, the earlier values up to the third count

.
counter values sum-value-quarterly
----------------------------------------------
1        10
2        14
3        16             40
4        20 
5        30
6        50             100 
7        25 
8        35
9        10              70
10       15
11       25

How do you set the condition for the program to carry up the above




The counter is say up to 24..
Posted
Updated 15-Feb-15 9:42am
v3
Comments
Kuthuparakkal 15-Feb-15 18:23pm    
Replace Inner SELECT UNION with your table name.

SELECT
[QGroup], SUM([values]) AS [sum-value-quarterly]
FROM
(
SELECT *, CEILING([counter] /3.0) AS [QGroup]
FROM
(
SELECT 1 AS [counter],10 AS [values]
UNION
SELECT 2 AS [counter],14 AS [values]
UNION
SELECT 3 AS [counter],16 AS [values]
UNION
SELECT 4 AS [counter],20 AS [values]
UNION
SELECT 5 AS [counter],30 AS [values]
UNION
SELECT 6 AS [counter],50 AS [values]
UNION
SELECT 7 AS [counter],25 AS [values]
UNION
SELECT 8 AS [counter],35 AS [values]
UNION
SELECT 9 AS [counter],10 AS [values]
UNION
SELECT 10 AS [counter],15 AS [values]
UNION
SELECT 11 AS [counter],25 AS [values]
)AS X
)AS Y
GROUP BY [QGroup]
ORDER BY [QGroup]

Check this approach:
SQL
select t1.value, t1.counter,
CASE WHEN t1.counter % 3 = 0 THEN (select sum(t2.value) from test t2 where (t2.counter-1) / 3 = (t1.counter-1) / 3)
ELSE NULL END as [sum-value-quarterly]
from test t1
 
Share this answer
 
Comments
Maciej Los 15-Feb-15 16:13pm    
+5
Replace Inner SELECT UNION with your table name.
SQL
SELECT
[QGroup], SUM([values]) AS [sum-value-quarterly]
FROM
(
    SELECT *, CEILING([counter] /3.0) AS [QGroup]
    FROM
    (
    SELECT 1 AS [counter],10 AS [values] 
    UNION
    SELECT 2 AS [counter],14 AS [values] 
    UNION
    SELECT 3 AS [counter],16 AS [values] 
    UNION
    SELECT 4 AS [counter],20 AS [values] 
    UNION
    SELECT 5 AS [counter],30 AS [values] 
    UNION
    SELECT 6 AS [counter],50 AS [values] 
    UNION
    SELECT 7 AS [counter],25 AS [values] 
    UNION
    SELECT 8 AS [counter],35 AS [values] 
    UNION
    SELECT 9 AS [counter],10 AS [values] 
    UNION
    SELECT 10 AS [counter],15 AS [values] 
    UNION
    SELECT 11 AS [counter],25 AS [values]
    )AS X
)AS Y
GROUP BY [QGroup]
ORDER BY [QGroup]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900