如何从表数据库中计算平均值

时间:2018-08-25 04:41:19

标签: php mysql sql average

我想从我的数据库中计算平均值。

例如,当我运行这样的SQL查询时

SELECT user.nama_u AS Nama_Siswa,
       nilai.nilai_n AS Nilai_Pelajaran
       FROM nilai,
            user
       WHERE nilai.id_sw = user.id_u
             AND user.pangkat_u = 'Siswa'
             AND nilai.kelas_n = 'I'
       ORDER BY user.nama_u DESC

我有这样的桌子

Nama_Siswa               Nilai_Pelajaran
===============          ===============     
Teuku Zul Hidayat        75
Teuku Zul Hidayat        60 
Ferry Mulia Ramadhani    100
Ferry Mulia Ramadhani    80
Apri Sara Diwa           80
Apri Sara Diwa           70

如果我想显示Nilai_Pelajaran的平均值,我从上面的sql查询中修改了什么?

因此表格必须是这样

Nama_Siswa               Average
===============          ===============     
Teuku Zul Hidayat        67.5
Ferry Mulia Ramadhani    90
Apri Sara Diwa           75

1 个答案:

答案 0 :(得分:2)

只需将查询更改为使用聚合函数(在本例中为AVG)和GROUP BY nama_u

SELECT user.nama_u AS Nama_Siswa, AVG(nilai.nilai_n) AS Nilai_Pelajaran 
FROM nilai
JOIN user 
WHERE nilai.id_sw = user.id_u AND user.pangkat_u = 'Siswa' AND nilai.kelas_n = 'I' 
GROUP BY user.nama_u
ORDER BY user.nama_u DESC