average在sql server中计算加权平均值

pgky5nke  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(394)

有人能解释一下为什么avg()函数在我的代码中给我一个加权平均数吗?

SELECT s.stud_id, s.country, SUM(e.paid) AS totalpaid
    INTO #totalpaid 
    FROM oc.students AS s
    JOIN oc.enrollment AS e ON s.stud_id = e.stud_id
GROUP BY s.country ,s.stud_id;

SELECT DISTINCT s.country, ROUND(AVG(t.totalpaid) OVER (PARTITION BY s.country),0) AS avg_country
    FROM #totalpaid t
    JOIN oc.students s ON t.stud_id = s.stud_id
    JOIN oc.enrollment e ON e.stud_id = s.stud_id;

例如,在马耳他,12名学生参加了1门课程,支付了45欧元,837名学生参加了7门课程,总共支付了294欧元。我想有一个简单的(45+294)/2的平均计算,但系统计算像(145+7294)/8。我做错什么了?

mzaanser

mzaanser1#

在第二个查询中,当您将temp表连接回 enrollment ,它为每个类生成一行;这就是 totalpaid 纵队是从哪里来的。
第二个查询没有使用任何不在temp表中的列,因此您根本不需要这些联接。这应该产生你想要的。

SELECT 
  t.country, 
  ROUND(AVG(t.totalpaid) OVER (PARTITION BY t.country),0) AS avg_country
FROM #totalpaid t
GROUP BY 
  t.country;
xxslljrj

xxslljrj2#

因为你两次加入你的table。
INSERT 以及 SELECT 您的查询语句等价于:

SELECT
  DISTINCT s.country, 
  ROUND(AVG(t.totalpaid) OVER (PARTITION BY s.country),0) AS avg_country
FROM (
  SELECT s.stud_id, s.country, SUM(e.paid) AS totalpaid
  FROM oc.students AS s
  JOIN oc.enrollment AS e ON s.stud_id = e.stud_id
  GROUP BY s.country ,s.stud_id    
) t
JOIN oc.students s ON t.stud_id = s.stud_id
JOIN oc.enrollment e ON e.stud_id = s.stud_id

在那里你可以清楚地看到table students 以及 enrollment 连接两次。这将产生一个倾斜的平均函数。

r55awzrz

r55awzrz3#

SELECT s.country, sum(e.paid) / count(DISTINCT s.stud_id) as average
FROM oc.students s 
JOIN oc.enrollment e ON e.stud_id = s.stud_id
GROUP BY s.country;
m3eecexj

m3eecexj4#

与此同时,我找到了解决办法:

SELECT
      country,
      ROUND(AVG(totalpaid) OVER (PARTITION BY country),0) AS avg_country
    FROM #totalpaid;

超级简单:)

相关问题