如何将查询从sql转换为codeigniter

时间:2019-02-28 06:12:03

标签: mysql sql codeigniter

这是我需要从SQL转换为CodeIgniter的查询:

SELECT b.bulan_tahun,b.kec, SUM(b.LFormal) AS LFormal, SUM(b.PFormal) AS PFormal, SUM(b.LFormal)+SUM(b.PFormal) AS SUMFormal,
SUM(b.LInformal) AS LInformal, SUM(b.PInformal) AS PInformal, SUM(b.LInformal)+SUM(b.PInformal) AS SUMInformal, SUM(b.LFormal)+ SUM(b.LInformal) AS LJumlah, 
SUM(b.PFormal)+SUM(b.PInformal) AS PJumlah,SUM(b.LFormal)+SUM(b.LInformal)+SUM(b.PFormal)+SUM(b.PInformal) AS SUMJUMLAH FROM
(SELECT a.bulan_tahun,a.kec,
(CASE WHEN a.sktor_pkrjaan='FORMAL' AND a.jk='L' THEN JJK ELSE 0 END) AS LFormal,
(CASE WHEN a.sktor_pkrjaan='FORMAL' AND a.jk='P' THEN JJK ELSE 0 END) AS PFormal,
(CASE WHEN a.sktor_pkrjaan='INFORMAL' AND a.jk='L' THEN JJK ELSE 0 END) AS LInformal,
(CASE WHEN a.sktor_pkrjaan='INFORMAL' AND a.jk='P' THEN JJK ELSE 0 END) AS PInformal
FROM
(SELECT id_tki,bulan_tahun,kec, COUNT(jk) AS JJK, sktor_pkrjaan, jk 
FROM tki
GROUP BY id_tki,bulan_tahun,kec, sktor_pkrjaan, jk) a
WHERE a.JJK>0) b
GROUP BY b.bulan_tahun,b.kec

我尝试在Active Record CodeIgniter上进行搜索,但未能获得答案。

谢谢。

2 个答案:

答案 0 :(得分:0)

$sql = "your query here";
$this->db->query($sql)->result();

答案 1 :(得分:0)

您可以尝试这样,按照活动记录对原始查询进行分区。

this->db->select("
SELECT b.bulan_tahun,b.kec, SUM(b.LFormal) AS LFormal, SUM(b.PFormal) AS PFormal, SUM(b.LFormal)+SUM(b.PFormal) AS SUMFormal,
SUM(b.LInformal) AS LInformal, SUM(b.PInformal) AS PInformal, SUM(b.LInformal)+SUM(b.PInformal) AS SUMInformal, SUM(b.LFormal)+ SUM(b.LInformal) AS LJumlah, 
SUM(b.PFormal)+SUM(b.PInformal) AS PJumlah,SUM(b.LFormal)+SUM(b.LInformal)+SUM(b.PFormal)+SUM(b.PInformal) AS SUMJUMLAH 
");
$this->db->from("
    (SELECT a.bulan_tahun,a.kec,
(CASE WHEN a.sktor_pkrjaan='FORMAL' AND a.jk='L' THEN JJK ELSE 0 END) AS LFormal,
(CASE WHEN a.sktor_pkrjaan='FORMAL' AND a.jk='P' THEN JJK ELSE 0 END) AS PFormal,
(CASE WHEN a.sktor_pkrjaan='INFORMAL' AND a.jk='L' THEN JJK ELSE 0 END) AS LInformal,
(CASE WHEN a.sktor_pkrjaan='INFORMAL' AND a.jk='P' THEN JJK ELSE 0 END) AS PInformal
(SELECT id_tki,bulan_tahun,kec, COUNT(jk) AS JJK, sktor_pkrjaan, jk 
FROM tki
GROUP BY id_tki,bulan_tahun,kec, sktor_pkrjaan, jk) a
WHERE a.JJK>0) b
");
$this->db->group_by("b.bulan_tahun,b.kec");
$data = $this->db->get()->result_array();