日期:2014-05-18  浏览次数:20580 次

一个求值的查询求助,比较简单,谢谢!
我有一些数据结构如下:

ID   COL1   COL2   COL3   COL4   COL5
0     20         -1     -2       3           8
1     6           0       5       -5           6
2     -5         -2       5     -2           -1

想从该表的结构上重新生成一列数据,这列的数据值就负数的总和,ID为关键列,在上面的假设数据中,重新生成的一列的值应该如下:

-3
-5
-10

请问SQL语句帮我解决,谢谢了。

------解决方案--------------------
还少了一项+(sign(COL5)-1)*COL5
------解决方案--------------------
select (case when col1 < 0 then col1 else 0 end ) + (case when col2 < 0 then col2 else 0 end ) + (case when col3 < 0 then col3 else 0 end )+(case when col4 < 0 then col4 else 0 end )+(case when col5 < 0 then col5 else 0 end ) from 表
------解决方案--------------------
create table #t(ID int,COL1 int,COL2 int,COL3 int,COL4 int,COL5 int)
insert into #t
select 0,20,-1,-2,3,8
union all select 1,6,0,5,-5,6
union all select 2,-5,-2,5,-2,-1

select case when col1> 0 then 0 else col1 end+
case when col2> 0 then 0 else col2 end+
case when col3> 0 then 0 else col3 end+
case when col4> 0 then 0 else col4 end+
case when col5> 0 then 0 else col5 end
from #t
/*
-----------
-3
-5
-10

(所影响的行数为 3 行)
*/