我需要将一列相加并除以另一列中的不同值
Column A Column B
10 James
20 Phill
02 James
10 Bill
23 Bill
14 James
我的答案需要是A栏(79)除以不同的James(3),PHILL(1),BILL(2)
的总和我的答案应该是:
James 26.333
Phil 79
Bill 39.5
我试过了:
select sum(column A)/distinct (column B)
答案 0 :(得分:1)
按名称汇总金额列和组。
SELECT Name,SUM(Amount)As Amt FROM TableName GROUP BY Name
我的结果:
Name Amt
Bill 33
James 26
Phill 20
您的问题已更改。我会更新答案......
SELECT (SELECT SUM(Amount) FROM TableName) / COUNT(Name) AS CalcAmount, Name
FROM TableName GROUP BY Name
结果:
CalcAmount Name
39 Bill
26 James
79 Phill
答案 1 :(得分:0)
select t1.sum_number/ count(t2.name), t2.name
from (
select sum(number) as sum_number
from t) as t1
join t as t2
join t as t3
on t2.name = t3.name
and t2.number = t3.number
group by t2.name
你可以摆弄它here
答案 2 :(得分:0)
您可以使用窗口函数执行此操作:
select columnB,
sum(sum(columnA)) over ()) / count(columnB) as YourAverage
from t
group by columnB;
Here是SQL小提琴。
答案 3 :(得分:0)
试试此代码
SELECT C2, MAX(A.SUMC1)/COUNT(C2) CalcAmount
FROM TableA,
(SELECT SUM(C1) SUMC1 FROM TableA) A
GROUP BY C2
它有效,我在SQLFiddle http://sqlfiddle.com/#!3/54794/6/0
中查看答案 4 :(得分:0)
试试这个, 假如说 : 表名=测试,列A =销售,列B =名称
SELECT a.name,
(SELECT SUM(b.sales) / COUNT(a.NAME) FROM test AS b)
FROM test AS a
GROUP BY NAME
答案 5 :(得分:0)
当您的DBMS支持“窗口功能”时,您可以执行以下操作:
SELECT ColB, CAST(SUM(SumA) OVER () AS FLOAT)/cnt CalcAmount
FROM
(
SELECT
ColB,
SUM(ColA) AS SumA,
COUNT(*) AS cnt
FROM TableA
GROUP BY ColB
) AS dt
如果ColA是INTEGER,则需要CAST(SUM(SumA)OVER()AS FLOAT / DECIMAL)以避免截断结果