Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
chih
Posting Yak Master
154 Posts |
Posted - 2009-10-20 : 20:15:42
|
| Hi All,here is the sample tableID price dates1 10 '2009-1-1'2 20 '2009-2-1'3 30 '2009-3-1'4 40 '2009-4-1'how can i get subtotal for each row? ID, price, dates, total1, 10, '2009-1-1', 102, 20, '2009-2-1', 30 3, 30, '2009-3-1', 604, 40, '2009-4-1', 100or is there a wasy i can get all id which total of price is less than 35 order by dates?the result should be ID, price, dates, total1, 10, '2009-1-1', 102, 20, '2009-2-1', 30 Thank you in advanced |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2009-10-20 : 20:36:17
|
| This will get your running total:INSERT INTO @TableSELECT 1 ,10 ,'2009-1-1' UNION ALLSELECT 2, 20 ,'2009-2-1' UNION ALLSELECT 3, 30 ,'2009-3-1' UNION ALLSELECT 4, 40 ,'2009-4-1'select t1.*,[Total] = sum(t2.price)from @table t1inner join @table t2on t1.id >= t2.idgroup byt1.id,t1.price,t1.datehaving sum(t2.price) < 35If you want all the records, just drop the HAVING partJimJim Everyday I learn something that somebody else already knew |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-10-21 : 12:34:41
|
| [code]select t.*from table touter apply(select sum(price) as prev from table where dates< t.dates)t1where t.price + isnull(prev,0)<=35[/code] |
 |
|
|
|
|
|
|
|