Click here to Skip to main content
15,907,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting sum from this table

HTML
id         type           num
220         2             10
220         2             10   
220         2             10
119         5             20     
119         5             20
117         1             9    
117         1             9
225         2             6 
225         2             6
227         2             1
228         2             4  

I am using this query:
SQL
select (sum(num))as dd from table1 where  type=2

result of this query is dd=47
but this wrong I want this result dd=21

In other words, DISTINCT id
i want this result
dd
21
Posted
Updated 3-Oct-14 1:37am
v3
Comments
George Jonsson 3-Oct-14 7:21am    
Have you tried using SELECT DISTINCT ?

SQL
select (sum(num))as dd from table1 where  type=2 group by id
 
Share this answer
 
Comments
saeed1364 3-Oct-14 7:35am    
i want result only sum
by group by get multi record in table
[no name] 3-Oct-14 13:00pm    
This answer looks pretty correct. What do you complain?
CPallini 3-Oct-14 7:44am    
Sorry?
You could try something like this:
SQL
--setup data
declare @table1 as table (pk int identity(1,1),id int,type int,num int);
insert into @table1 values(220,2,10);
insert into @table1 values(220,2,10);
insert into @table1 values(220,2,10);
insert into @table1 values(119,5,20);
insert into @table1 values(119,5,20);
insert into @table1 values(117,1,9);
insert into @table1 values(117,1,9);
insert into @table1 values(225,2,6);
insert into @table1 values(225,2,6);
insert into @table1 values(227,2,1);
insert into @table1 values(228,2,4);

--sum query
select (sum(num))as dd from
    (select distinct id, type, num  from @table1) table1
where type = 2;

In this example all 3 fields id, type and num are required to be distinct.
 
Share this answer
 
Please try like this:-
SELECT SUM(DISTINCT(num)) as dd from table1 where type=2


Follow this SQLfiddle[^]
Hope this helps
Thanks
:)
 
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