Please help. How to query this in CodeIgniter query builder. I don't know how to nested queries in codeigniter
select * from customer aa
left join (select a.customerId,
max(case
when b.domainValue = 'CEDC' then
IFNULL(b.value, 0)
end) 'CEDC',
max(case
when b.domainValue = 'PEDC' then
IFNULL(b.value, 0)
end) 'PEDC',
max(case
when b.domainValue = 'TPC' then
IFNULL(b.value, 0)
end) 'TPC',
max(case
when b.domainValue = 'SUAL' then
IFNULL(b.value, 0)
end) 'SUAL',
max(case
when b.domainValue = 'PAGBILAO' then
IFNULL(b.value, 0)
end) 'PAGBILAO'
from customer a
left join salescontractdetail b
on a.customerId = b.salesContractId
group by a.customerId) bb
on aa.customerId = bb.customerId
Thanks
Use db->query
$sql = "SELECT * ....."; # your formatted SQL query
$this->db->query($sql);
You can rewrite your query as below
SELECT c.*,
MAX(CASE WHEN s.domainValue = 'CEDC' THEN IFNULL(s.value, 0) ELSE 0 END) as CEDC,
MAX(CASE WHEN s.domainValue = 'PEDC' THEN IFNULL(s.value, 0) ELSE 0 END) PEDC,
MAX(CASE WHEN s.domainValue = 'TPC' THEN IFNULL(s.value, 0) ELSE 0 END) TPC,
MAX(CASE WHEN s.domainValue = 'SUAL' THEN IFNULL(s.value, 0) ELSE 0 END) SUAL,
MAX(CASE WHEN s.domainValue = 'PAGBILAO' THEN IFNULL(s.value, 0) ELSE 0 END) PAGBILAO
FROM customer c
LEFT JOIN salescontractdetail s ON c.customerId = s.salesContractId
GROUP BY c.customerId
Using active record it can be written something like below
$this->db->select("c.*,
MAX(CASE WHEN s.domainValue = 'CEDC' THEN IFNULL(s.value, 0) ELSE 0 END) as CEDC,
MAX(CASE WHEN s.domainValue = 'PEDC' THEN IFNULL(s.value, 0) ELSE 0 END) PEDC,
MAX(CASE WHEN s.domainValue = 'TPC' THEN IFNULL(s.value, 0) ELSE 0 END) TPC,
MAX(CASE WHEN s.domainValue = 'SUAL' THEN IFNULL(s.value, 0) ELSE 0 END) SUAL,
MAX(CASE WHEN s.domainValue = 'PAGBILAO' THEN IFNULL(s.value, 0) END ELSE 0 ) PAGBILAO", FALSE)
->from('customer as c')
->join("salescontractdetail as s", "c.customerId = s.salesContractId", "left")
->group_by("c.customerId")
->get()
;
$this->db->select('"c.*,
MAX(CASE WHEN s.domainValue = 'CEDC' THEN IFNULL(s.value, 0) ELSE 0 END) as CEDC,
MAX(CASE WHEN s.domainValue = 'PEDC' THEN IFNULL(s.value, 0) ELSE 0 END) PEDC,
MAX(CASE WHEN s.domainValue = 'TPC' THEN IFNULL(s.value, 0) ELSE 0 END) TPC,
MAX(CASE WHEN s.domainValue = 'SUAL' THEN IFNULL(s.value, 0) ELSE 0 END) SUAL,
MAX(CASE WHEN s.domainValue = 'PAGBILAO' THEN IFNULL(s.value, 0) END ELSE 0 )
PAGBILAO", FALSE);
$this->db->FROM('customer as c');
$this->db->join('salescontractdetail s', 'c.customerId =
s.salesContractId','left');
$this->db->group_by("c.customerId");
$query = $this->db->get()->result_array();
return $query;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.