使用SQL如何将表中的2列相乘并将它们的总和除以另一列的总和?
我的表格如下:
A | B | A*B
----|-----|------
1 | 2 | 2
5 | 4 | 20
3 | 5 | 15
让我们假设C = sum(A*B)
和D = sum(B)
。我想计算C/D
。
C = sum(A*B) = 37
和D = sum(B) = 11
以上C/D = 3.367
答案 0 :(得分:1)
这应该完全符合您的要求
SELECT (SUM(A*B)) / SUM(B) From table;
答案 1 :(得分:0)
试试这个:
SELECT f1, f2, (f2 / f1) as result from
(SELECT SUM(B) as f1, SUM(A*B) as f2 FROM table)
这将解决您的问题。
答案 2 :(得分:0)
我在SQL Server中尝试过类似的东西,可能会有所帮助:
DECLARE @table TABLE
(
A INT,
B INT
)
INSERT INTO @table
VALUES
(1,2),
(5,4),
(3,5)
SELECT SUM(a * b) [A*B],
SUM(b) [B],
CAST(SUM(a * b) / CAST(SUM(b) AS DECIMAL(13, 3)) AS DECIMAL(13, 3)) [RESULT]
FROM @table
答案 3 :(得分:0)
如果使用完整
,请尝试此操作CREATE TABLE #Table1
([Name] varchar(5), [Quality] int, [No] int)
;
INSERT INTO #Table1
([Name], [Quality], [No])
VALUES
( 'a' , 80 , 2),
('a', 85 , 3),
('a' , 90 , 4),
('b' , 85 , 2),
('b', 90, 1)
;
Declare @SumNo int,@DevideNo int,@Avg float
SET @SumNo=(SELECT SUM(Quality * No) as totalVal FROM #Table1)
SET @DevideNo=(SELECT SUM(Quality) FROM #Table1)
SET @Avg = @SumNo/@DevideNo
PRINT @Avg