从DB2中的别名获取最大值

时间:2012-12-14 03:45:23

标签: database db2

我想在我的别名中搜索最大值。这是我的查询

SELECT DISTINCT IPK.NIM,IPK.NAMA,IPK.IPK
FROM MAHASISWA M, PENILAIAN P, MATA_KULIAH MK, KRS K,
(SELECT M.NIM,M.NAMA, ROUND(SUM(P.ANGKA*MK.SKS)/SUM(MK.SKS),2) AS IPK
FROM MAHASISWA M, PENILAIAN P,MATA_KULIAH MK,KRS K
WHERE M.NIM=K.NIM AND MK.KODE_MK=K.KODE_MK AND K.NILAI=P.NILAI GROUP BY M.NIM,M.NAMA
) AS IPK
WHERE IPK.IPK=(SELECT MAX(IPK.IPK) FROM IPK);

但是当我运行它时,它说没有找到DB2ADMIN.IPK。我如何在查询中从我自己的别名中搜索它?

1 个答案:

答案 0 :(得分:0)

你应该可以这样做:

SELECT DISTINCT IPK.NIM,IPK.NAMA,IPK.IPK
    FROM MAHASISWA M, PENILAIAN P, MATA_KULIAH MK, KRS K,
    (
        SELECT M.NIM,M.NAMA, ROUND(SUM(P.ANGKA*MK.SKS)/SUM(MK.SKS),2) AS IPK
           FROM MAHASISWA M, PENILAIAN P,MATA_KULIAH MK,KRS K
           WHERE M.NIM=K.NIM AND MK.KODE_MK=K.KODE_MK AND K.NILAI=P.NILAI 
           GROUP BY M.NIM,M.NAMA
           ORDER BY IPK DESC
           FETCH FIRST ROW ONLY               
    ) AS IPK;

这将导致内部查询仅返回最大行。

以下是如何获得每个IPK的平均值:

SELECT IPK.NIM,IPK.NAMA, AVG(IPK.IPK)
    FROM MAHASISWA M, PENILAIAN P, MATA_KULIAH MK, KRS K
    (
        SELECT M.NIM,M.NAMA, ROUND(SUM(P.ANGKA*MK.SKS)/SUM(MK.SKS),2) AS IPK
           FROM MAHASISWA M, PENILAIAN P,MATA_KULIAH MK,KRS K
           WHERE M.NIM=K.NIM AND MK.KODE_MK=K.KODE_MK AND K.NILAI=P.NILAI 
           GROUP BY M.NIM,M.NAMA

    ) AS IPK
    GROUP BY IPK.NIM,IPK.NAMA;