0

我需要对一列求和并除以另一列中的不同值

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)
4

6 回答 6

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
于 2013-09-17T02:28:03.177 回答
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 是整数,则需要 CAST(SUM(SumA) OVER () AS FLOAT/DECIMAL) 以避免结果被截断

于 2013-09-17T06:13:50.543 回答
0

Try this one, assuming that : table name = test, Column A = sales, Column B = Name

     SELECT a.name, 
     (SELECT SUM(b.sales) / COUNT(a.NAME) FROM test AS b)
     FROM test AS a
     GROUP BY NAME
于 2013-09-17T04:23:28.057 回答
0

您可以使用窗口函数执行此操作:

select columnB,
       sum(sum(columnA)) over ()) / count(columnB) as YourAverage
from t
group by columnB;

是 SQL 小提琴。

于 2013-09-17T03:20:27.283 回答
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

于 2013-09-17T03:25:41.690 回答
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

你可以在这里摆弄它

于 2013-09-17T03:03:49.597 回答