2

我试图在 SQL 服务器上显示平均值,但是当我在 Excel 中测试数据时,结果不一样,肯定有一些明显的东西我遗漏了。

以下是 SQL Server 的代码和结果:

SELECT DISTINCT
d.d_reference + ' - ' + d.d_name AS Faculty,
AVG(sub.GroupSize) AS FacultyAverage


FROM
unitesnapshot.dbo.capd_register r
INNER JOIN unitesnapshot.dbo.capd_studentregister sr ON sr.sr_register = r.r_id
INNER JOIN unitesnapshot.dbo.capd_activity a ON a.a_register = r.r_id
INNER JOIN unitesnapshot.dbo.capd_moduleactivity ma ON ma.ma_activity = a.a_id
INNER JOIN unitesnapshot.dbo.capd_module m ON m.m_id = ma.ma_activitymodule
INNER JOIN unitesnapshot.dbo.capd_department d ON d.d_id = m.m_moduledept
INNER JOIN unitesnapshot.dbo.capd_section sec ON sec.s_id = m.m_modulesection
INNER JOIN (SELECT
            r.r_reference,
            COUNT(DISTINCT s.s_studentreference) AS GroupSize
            FROM
            unitesnapshot.dbo.capd_student s
            INNER JOIN unitesnapshot.dbo.capd_person p ON p.p_id = s.s_id
            INNER JOIN unitesnapshot.dbo.capd_studentregister sr ON sr.sr_student = p.p_id
            INNER JOIN unitesnapshot.dbo.capd_register r ON r.r_id = sr.sr_register
            GROUP BY
            r.r_reference) sub ON sub.r_reference = r.r_reference

WHERE
SUBSTRING(r.r_reference,4,2) = '12' AND
d.d_reference = '730'

GROUP BY
d.d_reference,
d.d_name

在此处输入图像描述

这是 Excel 中的结果:

在此处输入图像描述

谢谢

4

1 回答 1

5

试试这个好玩:

select avg(a)
from
    (values(1),(2),(3),(4)) x(a);

avg(a)
-------
2

AVG() 返回与基列相同的数据类型。如果您的列是int类型,那么结果也将被截断为int。下面返回“正确”的结果。

select avg(cast(a as decimal(10,5)))
from
    (values(1),(2),(3),(4)) x(a);

result
--------
2.5

您显示的差异(24 与 19.50484)很可能涉及与此相关的另一个错误。例如,要检查您在 Excel 中汇总的数据是否与在 SQL Server 中的相同,请将此结果转储到 Excel 中并进行汇总。如果它与您当前认为的 SQL Server 数据的 Excel等效数据不匹配,请将列对齐并检查它们是否具有相同的行数。然后按值 ASCENDING 对每一列进行单独排序并再次比较。

SELECT d.d_name, sub.GroupSize AS FacultyAverage
FROM unitesnapshot.dbo.capd_register r
INNER JOIN unitesnapshot.dbo.capd_studentregister sr ON sr.sr_register = r.r_id
INNER JOIN unitesnapshot.dbo.capd_activity a ON a.a_register = r.r_id
INNER JOIN unitesnapshot.dbo.capd_moduleactivity ma ON ma.ma_activity = a.a_id
INNER JOIN unitesnapshot.dbo.capd_module m ON m.m_id = ma.ma_activitymodule
INNER JOIN unitesnapshot.dbo.capd_department d ON d.d_id = m.m_moduledept
INNER JOIN unitesnapshot.dbo.capd_section sec ON sec.s_id = m.m_modulesection
INNER JOIN (SELECT r.r_reference,
            COUNT(DISTINCT s.s_studentreference) AS GroupSize
            FROM unitesnapshot.dbo.capd_student s
            INNER JOIN unitesnapshot.dbo.capd_person p ON p.p_id = s.s_id
            INNER JOIN unitesnapshot.dbo.capd_studentregister sr ON sr.sr_student = p.p_id
            INNER JOIN unitesnapshot.dbo.capd_register r ON r.r_id = sr.sr_register
            GROUP BY r.r_reference) sub ON sub.r_reference = r.r_reference
WHERE SUBSTRING(r.r_reference,4,2) = '12' AND d.d_reference = '730'
ORDER BY d.d_name
于 2013-04-24T10:08:03.490 回答