Click here to Skip to main content
16,011,647 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
Hi,
can sql's aggregate function SUM() be used with records of same value..?
for ex:
there is a table which has
table1

o_id Qty
a196 192
a196 496

can i use sum() function (select o_id,sum(qty) from table1 )in such scenario..?
Posted

Hi ,
Check this
SQL
select o_id,sum(qty) from table1 
GROUP BY o_id

Best Regards
M.Mitwalli
 
Share this answer
 
Hi,

Yes you can use, but you supposed to put an group by clause for other than Aggregate function columns.

e.g.
SQL
Select o_id,SUM(qty) From table1
GROUP BY o_id


this will work and gives you sum of qty and output is equal to 1 row only.

Regards,
V.J.
 
Share this answer
 
Comments
Member 8660975 30-May-12 2:15am    
thanks for the solution..
Prasad_Kulkarni 30-May-12 2:19am    
Formally 'Accept solution' if its really solves your problem
it is simple in group by give the column name on which you want to grouping

when you use this query
SQL
select o_id,sum(qty) from table1

it will return error
now you can write this query like that:-
SQL
select o_id,sum(qty) from table1 group by o_id


then it will not return error and give result of sum is:- either 192 or 496 is it correct.

if you want sum of 192 and 496 then you can write it as :-
SQL
select sum(qty) from table1 

then it will return 688.
 
Share this answer
 
Comments
Member 8660975 30-May-12 2:13am    
i want itz o_id also to be displayed..
If you run above query then It will throw below error

SQL
Msg 8120, Level 16, State 1, Line 10
Column 'table1.o_id 39; is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.



And to resolve this we need to add Group by clause like below

SQL
select o_id,sum(qty) from table1 GROUP BY o_id


Final result would be


o_idqty
a196688



Hope this helps , If yes then plz accept and vote the answer. Any queries / questions on this are always welcome.

Thanks & Regards
RDBurmon.Sr.Software Engineer
 
Share this answer
 
Comments
Member 8660975 30-May-12 2:30am    
yes it is working.
thank u so much..
RDBurmon 30-May-12 2:48am    
So if its working for you then let the other members know that you have solved your question and don't require any further attention for CP team by just accepting answer as "Accepted answer" and vote that answer . So that It will be frame in to top of all and good to go . Agreed Member 8****** ?

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