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 |
Nova
Starting Member
2 Posts |
Posted - 2014-11-07 : 14:34:40
|
I'm trying to write sum function in SQL with only basic operators without using aggregation function, but I don't know how or if it's possible or not!? I've searched but can't find anything on the internetFor example we have table order:OrderID ProductID Quantity----------------------------1001 15 51002 35 71002 10 101003 50 301004 47 15We can sum up the quantity with sum function in sqlSELECT SUM(Quantity) FROM OrderTableHow can I get the total quantity without using any aggregate functions? |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-11-07 : 15:04:11
|
dunno why you would want to, but here goes:DECLARE cur CURSOR FOR SELECT quantity FROM mytable;OPEN cur;DECLARE @total int = 0 , @qty int;FETCH NEXT FROM cur INTO @qty;WHILE @@fetch_status = 0 BEGIN SET @total+=@qty; FETCH NEXT FROM cur INTO @qty; END;CLOSE cur;DEALLOCATE cur;PRINT @total; |
|
|
Nova
Starting Member
2 Posts |
Posted - 2014-11-07 : 15:31:10
|
That’s perfect, Thanks gbritton |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2014-11-26 : 02:08:35
|
Why do you want to get SUM without using SUM function?MadhivananFailing to plan is Planning to fail |
|
|
|
|
|