Click here to Skip to main content
15,891,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a table which hold a ID and a Value.
ID    Value
2     100
5     250
8     150
12    200


Now I want a query which orders the Value column descending.
SQL
SELECT ID, Value 
FROM Values 
ORDER BY Value DESC


But it has to have another column(Total) where the value is added with each record, so the result will be this:
ID    Value   Total
5     250     250
12    200     400 (250 + 200)
8     150     550 (400 + 150)
2     100     650 (550 + 100)


How can I achive this?
Posted

 
Share this answer
 
Comments
Wendelius 9-May-12 13:58pm    
Hopefully that helps :)
The specific query in this case could be for example something like:
SQL
SELECT A.ID, 
       A.Value 
       (SELECT SUM(Value)
        FROM   Values B
        WHERE  B.Id <= A.Id) AS Total
FROM Values A
ORDER BY A.Value DESC
 
Share this answer
 
Comments
willempipi 14-May-12 9:57am    
I'm sorry, this is not the solution, since a higher ID is not automaticly a higher Value. Ended up making a C# program that simply counts the values because I hate SQL Cursors...
Wendelius 14-May-12 14:18pm    
Yes, the Id was used only as an example. In real situation yo umust use the column or columns that really define the order you want to use.
Use a cursor or write a C# app that counts the values, there's no SELECT statement for this.
 
Share this answer
 
see the below code..it will work

SQL
select a1.id,a1.value, sum(a2.value)
from Values a1, Values a2
where a1.id < a2.id or (a1.id = a2.id and a1.value=a2.value)
group by a1.id,a1.value
order by a1.id desc ,a1.value desc
 
Share this answer
 

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