[英]multiply rows in t-sql
I have following table 我有下表
ID Number
----------------
1 41.5
2 42.5
3 43.5
2 44.5
2 45.5
1 46.5
1 47.5
I need to write a query which will return distinct ID's and corresponding Number column values multiplied. 我需要编写一个查询,它将返回不同的ID和相应的Number列值相乘。 For the given table result should be like this
对于给定的表,结果应该是这样的
ID Result
-----------------
1 41.5 * 46.5 * 47.5
2 42.5 * 44.5 * 45.5
3 etc...
(without use cursors) (不使用游标)
SELECT Id, EXP(SUM(LOG(Number))) as Result
FROM Scores
GROUP BY id
This will work for positive numbers, to multiply negative numbers as well you can use ABS() function to use absolute (positive) value but final result will be positive rather than negative number: 这适用于正数,也可以乘以负数,你可以使用ABS()函数来使用绝对(正)值,但最终结果将是正数而不是负数:
SELECT Id, EXP(SUM(LOG(ABS(Number)))) as Result
FROM Scores
GROUP BY id
EDIT: Added test script 编辑:添加测试脚本
DECLARE @data TABLE(id int, number float)
INSERT INTO @data VALUES
(1, 2.2),
(1, 10),
(2, -5.5),
(2, 10)
SELECT Id, EXP(SUM(LOG(ABS(Number)))) as Result
FROM @data GROUP BY id
Output: 输出:
1 22
2 55
This is a slight variation on row concatenation and Jeff Moden has an excellent article on that at SQL Server Central titled Performance Tuning: Concatenation Functions and Some Tuning Myths 这是行连接的一个细微变化,Jeff Moden在SQL Server Central上有一篇很好的文章,标题为性能调优:连接函数和一些调整神话
Edit: @mellamokb It is analogous to concatenation, but requires some modification. 编辑:@mellamokb它类似于连接,但需要进行一些修改。 A sample script would be
一个示例脚本
create table testMult (id int, num int)
GO
insert into testMult values (1, 2)
insert into testMult values (1, 3)
insert into testMult values (1, 4)
insert into testMult values (2, 2)
GO
create function dbo.fnMult (@someId int)
returns int as
begin
declare @return int
set @return = 1
select @return = @return * num
from testMult
where id = @someId
return @return
end
GO
select *
from testMult
select t1.id,
dbo.fnMult(t1.id)
from testMult t1
group by t1.id
Which is just a very small variation on the script provided by Jeff Moden in his article. 这只是Jeff Moden在他的文章中提供的脚本的一个非常小的变化。
select id, power(sum(log10(num)),10) group by id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.