Click here to Skip to main content
16,016,500 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there, what I am trying to do is pull out data, and group by a relevant ID then add incremental dependant on the IDs, so for each of those ID rows I want to add 1 2 3 4 5 6 etc.

so for example
ID     -           Value
333     -          1
333      -         2
333       -        3
333        -       4
333         -      5

456          -     1
456           -    2
456            -   3

I have tried several scenarios but all failed... any ideas?
SQL
SELECT table1.choice1a, Sum(table1.choice1b) AS SumOchoice1b
FROM table1
GROUP BY table1.choice1a
HAVING (((table1.choice1a) Is Not Null));
Posted
Updated 23-Aug-11 19:33pm
v2
Comments
walterhevedeich 24-Aug-11 1:13am    
Which version of SQL are you using?

Use ROW_NUMBER() if you are using SQL 2005 or more..
Example:

SQL
SELECT table1.choice1a, table1.choice1b AS SumOchoice1b, row_number() over(partition by table1.choice1b order by table1.choice1b) as myrank 
FROM table1


check the following link for an example:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=139051[^]
 
Share this answer
 
Comments
Abhinav S 24-Aug-11 2:33am    
Good link. 5.
Depending on the version of your SQL Server, you can do the following:

SQL 2000
For SQL 2000, I believe there should be a unique ID for you to be able to do it. Not sure if there are solutions that does not require you to have a unique ID.
SQL
SELECT 
tbl2.PKID, -- this is your unique ID
tbl2.ID, 
(select count(1) from table1 where PKID <= tbl2.PKID and ID = tbl2.ID) AS RowNumber
from table1 tbl2
order by ID, RowNumber


SQL 2005
SQL
SELECT
tbl1.ID,
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS RowNumber
from table1 tbl1
 
Share this answer
 
Comments
Abhinav S 24-Aug-11 2:33am    
Good answer. My 5.
walterhevedeich 24-Aug-11 2:43am    
Thanks Abhinav.

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