select nested query CodeIgniter - php

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);
Read Regular Queries in codeigniter.com

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;

Related

COALESCE not returning an extra row for Null and 0 values

Currently I have 2 tables, the first table shows a count of statuses, refno. and agent_id(person in charge of the refno.) and the second table has an id and agent_name. So to refer a particular agent next to the refno. in table 1, you can reference it via the id of the agent table.
Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8b92273ef2bb807e3a23e4b8a2ce6d6b
Now I have found out that some of my listings have the agent_id as 0 and null, which doesn't have a reference in my agents table. So here I'm using COALESCE to add an extra row called Unassigned and inserting all variables with agent_id 0 or null inside this column. I've tried this same in my codeigniter model:
function get_totalagentstatus(){
$this->db->select("SUM(CASE WHEN t.status = 'D' THEN 1 END) AS draft,
SUM(CASE WHEN t.status = 'N' THEN 1 END) AS unpublish,
SUM(CASE WHEN t.status = 'Y' THEN 1 END) AS publish,
SUM(CASE WHEN t.status = 'U' THEN 1 END) AS action,
SUM(CASE WHEN t.status = 'L' THEN 1 END) AS unlisted,
SUM(CASE WHEN t.status = 'S' THEN 1 END) AS sold,
SUM(CASE WHEN t.status = 'T' THEN 1 END) AS let, COALESCE(c.display_name,'Unassigned'),
SUM(t.status = 'D') +SUM(t.status = 'N') + SUM(t.status = 'Y') + SUM(t.status = 'U') +
SUM(t.status = 'L' ) + SUM(t.status = 'S' )+ SUM(t.status = 'T' ) AS total, t.agent_id, c.display_name");
$this->db->from('crm_listings t');
$this->db->join('crm_clients_users c','t.agent_id = c.id');
$this->db->where('archive="N"');
$this->db->group_by('COALESCE(c.display_name,"Unassigned")');
$results = $this->db->get();
return $results;
}
Controller Class:
$content['total_agent_status'] = $this->leads_model->get_totalagentstatus()->result();
View Class:
<?php
foreach($total_agent_status as $row ){
$draft = $row->draft ? $row->draft : 0;
$unpublish = $row->unpublish ? $row->unpublish : 0;
$publish = $row->publish ? $row->publish : 0;
$action = $row->action ? $row->action : 0;
$unlisted = $row->unlisted ? $row->unlisted : 0;
$sold = $row->sold ? $row->sold : 0;
$let = $row->let ? $row->let : 0;
$total = $row->total ? $row->total : 0;
?>
<tr>
<td><?= $row->display_name ?></td>
<td><?= $draft ?></td>
<td><?= $unpublish ?></td>
<td><?= $publish ?></td>
<td><?= $action ?></td>
<td><?= $unlisted ?></td>
<td><?= $sold ?></td>
<td><?= $let ?></td>
<td><?= $total ?></td>
</tr>
I have done $this->db->last_query and got the following query:
SELECT SUM(CASE WHEN t.status = 'D' THEN 1 END) AS draft,
SUM(CASE WHEN t.status = 'N' THEN 1 END) AS unpublish,
SUM(CASE WHEN t.status = 'Y' THEN 1 END) AS publish,
SUM(CASE WHEN t.status = 'U' THEN 1 END) AS action,
SUM(CASE WHEN t.status = 'L' THEN 1 END) AS unlisted,
SUM(CASE WHEN t.status = 'S' THEN 1 END) AS sold,
SUM(CASE WHEN t.status = 'T' THEN 1 END) AS let,
COALESCE(c.display_name, 'Unassigned'), SUM(t.status = 'D')
+SUM(t.status = 'N') + SUM(t.status = 'Y') + SUM(t.status = 'U')
+ SUM(t.status = 'L' ) + SUM(t.status = 'S' )+ SUM(t.status = 'T' ) AS total,
`t`.`agent_id`, `c`.`display_name` FROM `crm_listings` `t`
JOIN `crm_clients_users` `c` ON `t`.`agent_id` = `c`.`id`
WHERE `archive` = "N" GROUP BY COALESCE(c.display_name, "Unassigned")
Now this returns everything except the Unassigned row which I want. I've also input this in my phpmyadmin to see the result and it does not return it there either, instead it shows the output with these headers and Unassigned is not there in any of the entries here:
You need a LEFT join of listings to agents if you want in the results the rows of listings that do not have a matching id in agents.
Also, you must group by COALESCE(t.agent_id, 0) to cover both cases of 0 and null in agent_id:
SELECT COALESCE(c.name, 'Unassigned') name,
SUM(CASE WHEN t.status = 'D' THEN 1 ELSE 0 END) AS draft,
SUM(CASE WHEN t.status = 'N' THEN 1 ELSE 0 END) AS unpublish,
SUM(CASE WHEN t.status = 'Y' THEN 1 ELSE 0 END) AS publish,
SUM(CASE WHEN t.status = 'U' THEN 1 ELSE 0 END) AS action,
SUM(CASE WHEN t.status = 'L' THEN 1 ELSE 0 END) AS unlisted,
SUM(CASE WHEN t.status = 'S' THEN 1 ELSE 0 END) AS sold,
SUM(CASE WHEN t.status = 'T' THEN 1 ELSE 0 END) AS let,
SUM(CASE WHEN t.status IN ('D', 'N', 'Y', 'U', 'L', 'S', 'T') THEN 1 ELSE 0 END) AS total
FROM listings t LEFT JOIN agents c
ON t.agent_id = c.id
GROUP BY COALESCE(t.agent_id, 0), c.name
ORDER BY c.name IS NULL, c.name;
I added an ELSE 0 part in all CASE expressions so that you get 0s in the results instead of NULLs and changed the expression to just 1 SUM for the column total by using the operator IN, but if 'D', 'N', 'Y', 'U', 'L', 'S' and 'T' are the only possible values of status then instead you can just use COUNT(*):
SELECT COALESCE(c.name, 'Unassigned') name,
SUM(CASE WHEN t.status = 'D' THEN 1 ELSE 0 END) AS draft,
SUM(CASE WHEN t.status = 'N' THEN 1 ELSE 0 END) AS unpublish,
SUM(CASE WHEN t.status = 'Y' THEN 1 ELSE 0 END) AS publish,
SUM(CASE WHEN t.status = 'U' THEN 1 ELSE 0 END) AS action,
SUM(CASE WHEN t.status = 'L' THEN 1 ELSE 0 END) AS unlisted,
SUM(CASE WHEN t.status = 'S' THEN 1 ELSE 0 END) AS sold,
SUM(CASE WHEN t.status = 'T' THEN 1 ELSE 0 END) AS let,
COUNT(*) AS total
FROM listings t LEFT JOIN agents c
ON t.agent_id = c.id
GROUP BY COALESCE(t.agent_id, 0), c.name
ORDER BY c.name IS NULL, c.name;
See the demo.

subqueries inside laravel raw syntax

I am trying to use DB::raw('raw sql query') to run the query below:
$rates = DB::raw('SELECT
mid,
x.qty_t/x.qty_total,
x.qty_t,
x.qty_total,
FROM
(SELECT
mid,
SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total,
SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t,
STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd
FROM
t_r
GROUP BY
mid) x')->get();
I'm getting a syntax error after (SELECT on mid, mtc and t_r.
How can I get this to work using raw?
You need to wrap DB::select around it. Something like this should work.
$rates = DB::select(DB::raw('SELECT
mid,
x.qty_t/x.qty_total,
x.qty_stddev,
x.qty_total,
FROM
(SELECT
mid,
SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total,
SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t,
STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd
FROM
t_r
GROUP BY
mid) x'))->get();

Combine queries.. PIVOT doesn't work

I have a problem with my queries. I have now 2 queries and that works fine. But when I want to add another query with a PIVOT, it doesn't work. I have tried a lot of things but nothing works..
This is my first two queries
$query = "SET SQL_BIG_SELECTS = 1;";
$query .= "SELECT * FROM datakram, datakram2, datakram3 WHERE datakram.NAME = datakram2.NAME AND datakram2.NAME = datakram3.NAME"
And I want to add a PIVOT for table "datakram4". But I want only the rows where the NAME is equal to the NAME in the others tables. Without the PIVOT it works..
My PIVOT code.
SELECT `name` ,
MAX( CASE WHEN `year` =2017 THEN `income` ELSE 0 END ) AS INCOME_2017,
MAX( CASE WHEN `year` =2017 THEN `expense` ELSE 0 END ) AS EXPENSE_2017,
MAX( CASE WHEN `year` =2016 THEN `income` ELSE 0 END ) AS INCOME_2016,
MAX( CASE WHEN `year` =2016 THEN `expense` ELSE 0 END ) AS EXPENSE_2016
FROM `test_data` GROUP BY `name`
I use multi_query for my php script.
Simply join the queries:
SELECT d4.*
FROM datakram d1
INNER JOIN datakram2 d2
ON d1.`NAME` = d2.`NAME`
INNER JOIN datakram3 d3
ON d2.`NAME` = d3.`NAME`
INNER JOIN
(SELECT `name` ,
MAX(CASE WHEN `year`=2017 THEN `income` ELSE 0 END) AS INCOME_2017,
MAX(CASE WHEN `year`=2017 THEN `expense` ELSE 0 END) AS EXPENSE_2017,
MAX(CASE WHEN `year`=2016 THEN `income` ELSE 0 END) AS INCOME_2016,
MAX(CASE WHEN `year`=2016 THEN `expense` ELSE 0 END) AS EXPENSE_2016
FROM `test_data`
GROUP BY `name`
) d4
ON d3.`NAME` = d4.`name`
A simple way is to filter in the WHERE clause:
SELECT `name` ,
MAX(CASE WHEN `year` = 2017 THEN `income` ELSE 0 END) AS INCOME_2017,
MAX(CASE WHEN `year` = 2017 THEN `expense` ELSE 0 END) AS EXPENSE_2017,
MAX(CASE WHEN `year` = 2016 THEN `income` ELSE 0 END) AS INCOME_2016,
MAX(CASE WHEN `year` = 2016 THEN `expense` ELSE 0 END) AS EXPENSE_2016
FROM `test_data` td
WHERE EXISTS (SELECT 1 FROM FROM datakram d WHERE d.name = td.NAME) AND
EXISTS (SELECT 1 FROM FROM datakram2 d WHERE d.name = td.NAME) AND
EXISTS (SELECT 1 FROM FROM datakram3 d WHERE d.name = td.NAME)
GROUP BY `name` ;

Using SET #var_name in mysql giving syntax error

I am using below mysql query using php to run my report for users
SET #p_yyyy_1 = ".$year[0].";
SET #p_q_1 = '".$quarter[0]."';
SET #p_yyyy_2 = ".$year[1].";
SET #p_q_2 = '".$quarter[1]."';
SET #p_yyyy_3 = ".$year[2].";
SET #p_q_3 = '".$quarter[2]."';
SET #p_yyyy_4 = ".$year[3].";
SET #p_q_4 = '".$quarter[3]."';
select pr.profile_id
, max(pr.fname) fname, max(pr.lname) lname
, max(case when p.year = #p_yyyy_1 and p.quarter = #p_q_1 then p.grade else null end) PPT_Q1
, max(case when p.year = #p_yyyy_2 and p.quarter = #p_q_2 then p.grade else null end) PPT_Q2
, max(case when p.year = #p_yyyy_3 and p.quarter = #p_q_3 then p.grade else null end) PPT_Q3
, max(case when p.year = #p_yyyy_4 and p.quarter = #p_q_4 then p.grade else null end) PPT_Q4
, max(case when b.year = #p_yyyy_1 and b.quarter = #p_q_1 then b.grade else null end) BPET_Q1
, max(case when b.year = #p_yyyy_2 and b.quarter = #p_q_2 then b.grade else null end) BPET_Q2
, max(case when b.year = #p_yyyy_3 and b.quarter = #p_q_3 then b.grade else null end) BPET_Q3
, max(case when b.year = #p_yyyy_4 and b.quarter = #p_q_4 then b.grade else null end) BPET_Q4
, max(case when bo.year = #p_yyyy_1 and bo.quarter = #p_q_1 then bo.grade else null end) BOAC_Q1
, max(case when bo.year = #p_yyyy_2 and bo.quarter = #p_q_2 then bo.grade else null end) BOAC_Q2
, max(case when bo.year = #p_yyyy_3 and bo.quarter = #p_q_3 then bo.grade else null end) BOAC_Q3
, max(case when bo.year = #p_yyyy_4 and bo.quarter = #p_q_4 then bo.grade else null end) BOAC_Q4
, max(case when f.year = #p_yyyy_1 and f.quarter = #p_q_1 then f.grade else null end) FIRING_Q1
, max(case when f.year = #p_yyyy_2 and f.quarter = #p_q_2 then f.grade else null end) FIRING_Q2
, max(case when f.year = #p_yyyy_3 and f.quarter = #p_q_3 then f.grade else null end) FIRING_Q3
, max(case when f.year = #p_yyyy_4 and f.quarter = #p_q_4 then f.grade else null end) FIRING_Q4
from profile_header pr
cross join (
select #p_yyyy_1 yyyy, #p_q_1 q
union select #p_yyyy_2, #p_q_2
union select #p_yyyy_3, #p_q_3
union select #p_yyyy_4, #p_q_4
) yq
left join ppt_header ph on ph.profile_id = pr.profile_id
and ph.delete_flag = 'n'
left join ppt p on ph.ppt_header_id = p.ppt_header_id
and p.year = yq.yyyy
and p.quarter = yq.q
left join bpet_header bh on bh.profile_id = pr.profile_id
and bh.delete_flag = 'n'
left join bpet b on bh.bpet_header_id = b.bpet_header_id
and b.year = yq.yyyy
and b.quarter = yq.q
left join baoc_header boh on boh.profile_id = pr.profile_id
and boh.delete_flag = 'n'
left join baoc bo on boh.baoc_header_id = bo.baoc_header_id
and bo.year = yq.yyyy
and bo.quarter = yq.q
left join firingqt_header fh on fh.profile_id = pr.profile_id
and fh.delete_flag = 'n'
left join firing_qt f on fh.firingqt_header_id = f.firingqt_header_id
and f.year = yq.yyyy
and f.quarter = yq.q
left join lookup l1 on pr.group_id = l1.lookup_id
left join lookup l2 on pr.hit_no = l2.lookup_id
where pr.profile_id IN ($commando)
group by pr.profile_id
ORDER BY 2 ASC, 3 ASC
When I am running this query directly in phpmyadmin query tab, it's working perfectly, but when I run this query through my php file and script I get this mysql error :
MySQL Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'SET #p_q_1 = 'Q1'; SET #p_yyyy_2 = 2014; SET #p_q_2 = 'Q4';
SET #p_y' at line 2

mysql query not working when add where condition

SELECT tm.MAGAZINE_ID,`MAGAZINE_NAME`,
CASE WHEN tsd.no_of_issues IS NULL THEN 1 ELSE tsd.no_of_issues
END AS Subscription_Type,
sum(tu.units) AS Total_sales,
SUM(CASE WHEN customer_currency='USD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_USD,
SUM(CASE WHEN customer_currency='CAD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_CAD,
SUM(CASE WHEN customer_currency='CNY' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_CNY,
SUM(CASE WHEN customer_currency='EUR' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_EUR,
SUM(CASE WHEN customer_currency='GBP' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_GBP,
SUM(CASE WHEN customer_currency='AUD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_AUD,
SUM(CASE WHEN customer_currency='MXN' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_MXN,
SUM(CASE WHEN customer_currency='CHF' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_CHF,
SUM(CASE WHEN customer_currency='NZD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_NZD,
SUM(CASE WHEN customer_currency='DKK' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_DKK,
SUM(CASE WHEN customer_currency='NOK' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_NOK,
SUM(CASE WHEN customer_currency='JPY' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_JPY,
SUM(CASE WHEN customer_currency='SEK' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_SEK,
SUM(CASE WHEN customer_currency='SGD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_SGD,
SUM(CASE WHEN customer_currency='TWD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_TWD,
SUM(CASE WHEN customer_currency='HKD' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_HKD,
SUM(CASE WHEN customer_currency='CNY' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_CNY,
SUM(CASE WHEN customer_currency='IDR' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_IDR,
SUM(CASE WHEN customer_currency='AED' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_AED,
SUM(CASE WHEN customer_currency='SAR' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_SAR,
SUM(CASE WHEN customer_currency='ILS' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_ILS,
SUM(CASE WHEN customer_currency='RUB' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_RUB,
SUM(CASE WHEN customer_currency='ZAR' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_ZAR,
SUM(CASE WHEN customer_currency='TRY' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_TRY,
SUM(CASE WHEN customer_currency='INR' THEN tu.developer_proceeds * tu.units ELSE 0 END) AS Revenue_INR
FROM `tbl_itunes_report` tu
LEFT JOIN tbl_magazine_subscription_dtl tsd ON tsd.subscription_key = tu.sku_key AND ((tu.begin_date >= tsd.start_date AND tu.begin_date < tsd.end_date) OR (tu.begin_date >= tsd.start_date AND tsd.end_date = '0000-00-00'))
LEFT JOIN tbl_magazine_subscription ts ON ts.magazine_subscription_id = tsd.subs_id LEFT JOIN tbl_magazine_issue ti ON ti.PurchaseKey = tu.sku_key AND ti.OS_SELECT = 0
LEFT JOIN tbl_magazine tm ON tm.magazine_id = ts.magazine_id OR tm.magazine_id = ti.magazine_id
WHERE `product_type_identifier` LIKE 'IA%'
AND ( tsd.subscription_key IS NOT NULL OR ti.PurchaseKey IS NOT NULL )
AND tu.report_from = 'ecmedia' AND `units` >0 AND tu.begin_date >= "2013-12-01"
AND tu.begin_date <= "2013-12-21" AND tm.publisher_id = 120
GROUP BY tm.MAGAZINE_ID,tsd.no_of_issues
ORDER BY tm.magazine_name,tsd.no_of_issues
I am using this query for my report generation. When I am executing this query with out
tm.publisher_id = 120.
It works normally, but when I add that in to my query the execution time increases. Is there anything wrong with this query that you see?
Apart from the proper indexing, since you're using an outer join you most likely want to move any condition that you apply to the table on right of LEFT JOIN (tm.publisher_id = 120) from WHERE clause to ON clause of that join
...
LEFT JOIN tbl_magazine tm
ON (tm.magazine_id = ts.magazine_id OR
tm.magazine_id = ti.magazine_id)
AND tm.publisher_id = 120
...

Categories