这个SQL语句如何写,在线等,有效立给分
表 : FIELDS1 FIELDS2
221 1
23349.88 1
651 1
182 0
346 1
3543 0
目的:sum(fields1)。
条件:当 fields2=1 时作为正数;当fields2=0 时作为负数。
需求:一条语句解决
用CASE可以达到目的吗?
问题点数:100、回复次数:7Top
1 楼guanshiyu123(就欺负你..宝)回复于 2004-12-02 22:48:19 得分 0
select sum(fields) from
(select sum(fields1) fields from ttt where FIELDS2=1
union all
select -sum(fields1) fields from ttt where FIELDS2=0) aTop
2 楼guanshiyu123(就欺负你..宝)回复于 2004-12-02 22:51:13 得分 0
测试数据
create table ttt (FIELDS1 dec, FIELDS2 int)
insert ttt
select 221, 1
union
select 23349.88 , 1
union
select 651 , 1
union
select 182, 0
union
select 346 , 1
union
select 3543, 0Top
3 楼guanshiyu123(就欺负你..宝)回复于 2004-12-02 22:52:49 得分 0
因把fields1的数据类型定为dec,所以把小数点后面的都忽略了Top
4 楼hdhai9451(☆新人类☆)回复于 2004-12-02 22:53:36 得分 0
select FIELDS1 =sum(case when FIELDS2=1 then FIELDS1 else -FIELDS1 end ) from tbTop
5 楼guanshiyu123(就欺负你..宝)回复于 2004-12-02 22:53:47 得分 0
结果
fields
20843
Top
6 楼hdhai9451(☆新人类☆)回复于 2004-12-02 22:57:25 得分 50
create table tb(FIELDS1 numeric(18,2),FIELDS2 int)
Insert into tb
select '221','1'
union all select '23349.88','1'
union all select '651','1'
union all select '182','0'
union all select '346','1'
union all select '3543','0'
select FIELDS1 =sum(case when FIELDS2=1 then FIELDS1 else -FIELDS1 end ) from tb
結果:20842.88
樓主想要的是不是這個結果?
Top
7 楼mastersky(浪)回复于 2004-12-03 00:14:26 得分 50
create table tb1(FIELDS1 numeric(18,2),FIELDS2 int)
Insert into tb1
select '221','1'
union all select '23349.88','1'
union all select '651','1'
union all select '182','0'
union all select '346','1'
union all select '3543','0'
--可以不用case
select sum(Fields1 * (Fields2+Fields2-1) ) as 合计 from tb1
结果:
合计
----------------------------------------
20842.88
(所影响的行数为 1 行)
Top




