如何使用sumfor这个表 [英] how use sumfor this table

查看:135
本文介绍了如何使用sumfor这个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这张桌子得到的数额



 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



我正在使用此查询:

 选择(sum(num))作为 dd 来自 table1 其中 type = 2 



此查询的结果是dd = 47

但这个错了我想要这个结果dd = 21



换句话说,DISTINCT id

i想要这个结果

dd

21

解决方案

  select (sum(num)) as  dd 来自 table1 其中 type = 2  group   by  id 


您可以尝试这样的事情:

   -   设置数据 
声明 @ table1 as table (pk int identity 1 ,< span class =code-digit> 1 ),id int type int ,num int );
插入 进入 @ table1 220 2 10 );
插入 进入 @ table1 220 2 10 );
插入 进入 @ table1 220 2 10 );
插入 进入 @ table1 119 5 20 );
插入 进入 @ table1 119 5 20 );
插入 进入 @ table1 117 1 9 );
插入 进入 @ table1 117 1 9 );
插入 进入 @ table1 225 2 6 );
插入 进入 @ table1 225 2 6 );
插入 进入 @ table1 227 2 1 );
插入 进入 @ table1 228 2 4 );

- 总和查询
选择(sum(num))作为 dd 来自
select distinct id, type ,num 来自 @ table1 )table1
其中 类型 = 2 ;



In这个例子所有3个字段的id,type和num都必须是不同的。


请尝试这样: -

 SELECT SUM( DISTINCT(num))作为来自table1的dd,其中type = 2 





关注此SQLfiddle [ ^ ]

希望这有帮助

谢谢

:)


I am getting sum from this table

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:

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

解决方案

select (sum(num))as dd from table1 where  type=2 group by id


You could try something like this:

--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.


Please try like this:-

SELECT SUM(DISTINCT(num)) as dd from table1 where type=2



Follow this SQLfiddle[^]
Hope this helps
Thanks
:)


这篇关于如何使用sumfor这个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆