September 29, 2010 at 12:28 pm
Hi All,
I have the data as shown below
id value
1 0
2 1
3 1
4 1
5 1
6 1
if the above is the input from sql..say I want the output in csv and the out should look like this
id Value
1 5 (sum of 2 to 6 id's)
2 0
3 0
4 0
5 0
6 0
Could anyone give me any idea's...we can also say id "1 " is of different type and id's from 2 to 6 are of different type.
Thanks,
September 29, 2010 at 12:49 pm
Would you please clarify your requirement? What would be the criteria to do the aggregation?
Based on your rather vague example it seems like you want to count the rows with a consecutive value of 1 after a row with a value of Zero. Just guessing...
But in that case it wouldn't be "sum of 2 to 5 id's" but sum of id=2 to id=6.
Side note: Are the values in the id column guaranteed to have no gaps?
September 29, 2010 at 12:51 pm
Hey You are right it is sum of 2 to 6. This is a example of what I have to do?
more detail
idtype id value
A 1 0
B 2 1
B 3 1
B 4 1
B 5 1
B 6 1
we have to sum all the values of type B and then add with value is type A and put the result in the value of type A and make all the values of type b to ZERO
And the id columns make have gap
September 29, 2010 at 1:06 pm
Something like this?
DECLARE @tbl TABLE
(
idtype CHAR(1), id INT, VALUE INT
)
INSERT INTO @tbl
SELECT 'A', 1 ,0 UNION ALL
SELECT 'B', 2 ,1 UNION ALL
SELECT 'B', 3 ,1 UNION ALL
SELECT 'B', 4 ,1 UNION ALL
SELECT 'B', 5 ,1 UNION ALL
SELECT 'B', 6, 1
;
WITH cte AS
(
SELECT SUM(VALUE) AS total
FROM @tbl
WHERE idtype ='B'
)
SELECT
idtype,
CASE WHEN idtype ='A' THEN total ELSE 0 END AS new_value
FROM @tbl
CROSS JOIN cte
September 29, 2010 at 3:19 pm
Hey Thanks very much for the immediate response. I will try to implement this.
September 30, 2010 at 7:18 am
here it is that we just have 5 records but what if we have millions of records to be inserted to the temp table
September 30, 2010 at 12:29 pm
Will try to post it in a proper way. Thanks for the guidance.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply