1  /  1  页   1 跳转 查看:1892

[技术文档] 用集合的方式求积

用集合的方式求积

我们知道可以用集合的方式求和,直接用sum即可,今天看到一个帖子,可以象用Sum求和的方式求积,整理了一下,不错的方法:

create table t
(
num int
)

insert into t select 5
insert into t select 2
insert into t select 3
insert into t select -1

go
SELECT EXP(SUM(LOG(abs(num))))*power(-1,(select count(*) from t where num<0)) from t
go

insert into t select -2
SELECT EXP(SUM(LOG(abs(num))))*power(-1,(select count(*) from t where num<0)) from t

go
虽有智慧,不如乘势;虽有鎡基,不如待时。
君子学以聚之,问以辨之,宽以居之,仁以行之。
独学而无友,则孤陋而寡闻。
 

回复:用集合的方式求积

狼,有0 值,没有考虑。
 

回复: 用集合的方式求积



引用:
原帖由 jixiaojie 于 2009-3-19 17:58:00 发表
狼,有0 值,没有考虑。


有道理,大家自行考虑哈,吼吼
虽有智慧,不如乘势;虽有鎡基,不如待时。
君子学以聚之,问以辨之,宽以居之,仁以行之。
独学而无友,则孤陋而寡闻。
 

回复:用集合的方式求积

替换power函数的部分
SELECT EXP(SUM(LOG(ABS(num))))*(SUM(CASE WHEN SIGN(num)=-1 THEN -1 ELSE 0 END)%2) from t
 

回复:用集合的方式求积

考虑0值再加个case 判断吧,或者 ELSE 0 -》 ELSE -2
 

回复:用集合的方式求积

我前面的写法有错误
这样可以了
SELECT EXP(SUM(LOG(ABS(num))))*(case when SUM(CASE WHEN SIGN(num)=-1 THEN -1 ELSE 0 END)%2=0 then 1 else -1 end) from t
 

回复: 用集合的方式求积

create table t
(
num int
)
insert into t select 5
insert into t select 2
insert into t select 3
insert into t select -1
go

;with nt as
(
select id=row_number() over (order by num), num from t
)
, cte as
(
select id, num from nt where id=1
union all
select nt.id, num=nt.num*cte.num
from nt join cte on nt.id=cte.id+1
)
select top 1 num from cte
order by id desc

/*
-30
*/


insert t select -2

;with nt as
(
select id=row_number() over (order by num), num from t
)
, cte as
(
select id, num from nt where id=1
union all
select nt.id, num=nt.num*cte.num
from nt join cte on nt.id=cte.id+1
)
select top 1 num from cte
order by id desc

/*
60
*/

drop table t
 
一错再错,继续错就对了。
  
 

回复:用集合的方式求积

好东西啊 学习了
 
1  /  1  页   1 跳转

版权所有 微软BI开拓者 

Powered by Discuz!NT 2.1.202    Copyright © 2001-2010 Comsenz Inc.
Processed in 0.0312504 second(s) , 4 queries.
返顶部