如何在此查询中插入临时(不插入表)?

时间:2016-08-02 08:20:46

标签: sql oracle10g

select * 
from
(
    select temp.agamaid, temp.jum_peg, nvl(temp.jeniskelamin,'L') jeniskelamin,
           case when temp.jeniskelamin = 'L' then 1
                when temp.jeniskelamin = 'P' then 2
                else 0
           end as num
    from
    (
        select agama.agamaid, AGAMA.agama, PEGAWAI.jeniskelamin,
               count(PEGAWAI.pegawaiid) jum_peg
        from agama
            left join pegawai on PEGAWAI.agamaid = AGAMA.agamaid
        group by AGAMA.agamaid, AGAMA.agama, PEGAWAI.jeniskelamin
    ) temp 
) temp
    left join master_jeniskelamin mjk on temp.jeniskelamin = mjk.id_jk
order by temp.agamaid, temp.jeniskelamin

该查询只是给我一个这样的结果:

Not my expectation output

但是我想要结果,(3,4,5)中的agamaid还有另一个还没有的jeniskelamin。

你能帮帮我吗? :)

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    a.agamaid,
    COUNT(p.pegawaiid) AS jum_peg,
    p.jeniskelamin,
    CASE
        WHEN p.jeniskelamin = 'L' THEN 1
        WHEN p.jeniskelamin = 'P' THEN 2
        ELSE 0
    END AS num,
    mjk.id_jk
FROM
    master_jeniskelamin mjk
    CROSS JOIN agama a
    LEFT JOIN pegawai p
        ON p.jeniskelamin = mjk.id_jk
        AND p.agamaid = a.agamaid
GROUP BY
    a.agamaid,
    mjk.id_jk,
    p.jeniskelamin
ORDER BY
    a.agamaid,
    mjk.id_jk