How to join 2 queries - mysql

I have 2 SQL queries:
SELECT accounts.assigned_user_id, jt0.user_name assigned_user_name,
SUM( IF(opp.opportunity_type='2', IFNULL(opp.amount,0), 0) ) AS amt_revenue,
SUM( IF(opp.opportunity_type='4', IFNULL(opp.amount,0), 0) ) AS amt_return
FROM accounts
LEFT JOIN users jt0
ON jt0.id=accounts.assigned_user_id AND jt0.deleted=0 AND jt0.deleted=0
LEFT JOIN accounts_opportunities AS a_o
ON a_o.account_id = accounts.id AND a_o.deleted=0
LEFT JOIN opportunities AS opp
ON (opp.id = a_o.opportunity_id AND opp.deleted=0 AND opp.sales_stage = 'Closed Won' AND opp.opportunity_type IN('2', '4'))
WHERE accounts.deleted=0
GROUP BY accounts.assigned_user_id, jt0.user_name
ORDER BY SUM(IFNULL(opp.amount,0)) DESC
And:
SELECT accounts.assigned_user_id,
SUM( IFNULL(accounts_collections.amount,0)) AS amount
FROM accounts
LEFT JOIN accounts_collections ON(accounts_collections.account_id = accounts.id AND accounts_collections.deleted=0)
GROUP BY accounts.assigned_user_id
How can I join the 2 queries above?

You may be able to put the second query into a subselect. There are two ways of doing this. In the select section or in the form section. Not sure which MySQL accepts but both work in other SQL engines.
SELECT
accounts.assigned_user_id,
jt0.user_name assigned_user_name,
SUM( IF(opp.opportunity_type='2',
IFNULL(opp.amount,0), 0)
) AS amt_revenue,
SUM( IF(opp.opportunity_type='4',
IFNULL(opp.amount,0), 0)
) AS amt_return,
(
SELECT SUM( IFNULL(accounts_collections.amount,0)) AS amount
FROM accounts
LEFT JOIN accounts_collections ON(accounts_collections.account_id = accounts.id AND accounts_collections.deleted=0)
GROUP BY accounts.assigned_user_id
) AS amount
FROM accounts
LEFT JOIN users jt0
ON jt0.id=accounts.assigned_user_id AND jt0.deleted=0 AND jt0.deleted=0
LEFT JOIN accounts_opportunities AS a_o
ON a_o.account_id = accounts.id AND a_o.deleted=0
LEFT JOIN opportunities AS opp
ON (opp.id = a_o.opportunity_id AND opp.deleted=0 AND opp.sales_stage = 'Closed Won' AND opp.opportunity_type IN('2', '4'))
WHERE accounts.deleted=0
GROUP BY accounts.assigned_user_id, jt0.user_name
ORDER BY SUM(IFNULL(opp.amount,0)) DESC
SELECT
accounts.assigned_user_id,
jt0.user_name assigned_user_name,
SUM( IF(opp.opportunity_type='2',
IFNULL(opp.amount,0), 0)
) AS amt_revenue,
SUM( IF(opp.opportunity_type='4',
IFNULL(opp.amount,0), 0)
) AS amt_return,
amount_tbl.amount
FROM accounts
LEFT JOIN users jt0
ON jt0.id=accounts.assigned_user_id AND jt0.deleted=0 AND jt0.deleted=0
LEFT JOIN accounts_opportunities AS a_o
ON a_o.account_id = accounts.id AND a_o.deleted=0
LEFT JOIN opportunities AS opp
ON (opp.id = a_o.opportunity_id AND opp.deleted=0 AND opp.sales_stage = 'Closed Won' AND opp.opportunity_type IN('2', '4'))
JOIN (
SELECT accounts.assigned_user_id,
SUM( IFNULL(accounts_collections.amount,0)) AS amount
FROM accounts
LEFT JOIN accounts_collections ON(accounts_collections.account_id = accounts.id AND accounts_collections.deleted=0)
GROUP BY accounts.assigned_user_id
) AS amount_tbl ON (amount_tbl.assigned_user_id = accounts.assigned_user_id)
WHERE accounts.deleted=0
GROUP BY accounts.assigned_user_id, jt0.user_name
ORDER BY SUM(IFNULL(opp.amount,0)) DESC

Related

sql join and sum 3

I have problem with join and sum column. My query is
SELECT
sum(IFNULL(`worker_hours`.`godziny`, 0)) as godziny,
sum(IFNULL(`worker_hours`.`wartosc`, 0)) as wartosc,
sum(IFNULL(`worker_cashes`.`kwota`, 0)) as kwota,
`workers`.*
FROM
`workers`
LEFT join `worker_hours` on `worker_hours`.`pracownik` = `workers`.`id`
LEFT join `worker_cashes` on `worker_cashes`.`pracownik` = `workers`.`id`
WHERE `workers`.`id_user` = '3'
group by
`workers`.`id`
The result sum *2 my query, what i do wrong? in i have this query is fine:
SELECT
sum(IFNULL(`worker_hours`.`godziny`, 0)) as godziny,
sum(IFNULL(`worker_hours`.`wartosc`, 0)) as wartosc,
`workers`.*
FROM
`workers`
left join `worker_hours` on `worker_hours`.`pracownik` = `workers`.`id`
WHERE `workers`.`id_user` = '3'
group by
`workers`.`id`
the problem is the second left join
You should aggregate first in the tables worker_hours and worker_cashes and then join workers to the resultsets of the aggregations so that you don't get the same row multiple times due to the multiple joins:
SELECT w.*,
COALESCE(h.godziny, 0) AS godziny,
COALESCE(h.wartosc, 0) AS wartosc,
COALESCE(c.kwota, 0) AS kwota
FROM workers AS w
LEFT JOIN (
SELECT pracownik,
SUM(godziny) AS godziny,
SUM(wartosc) AS wartosc
FROM worker_hours
GROUP BY pracownik
) AS h ON h.pracownik = w.id
LEFT JOIN (
SELECT pracownik,
SUM(kwota) AS kwota
FROM worker_cashes
GROUP BY pracownik
) AS c ON c.pracownik = w.id
WHERE w.id_user = '3';

How to fix MySQL query not to return nulls

Here is my query,
SELECT
p.pcode,
p.productName,
s.pcode,
MAX(s.in_stock) AS opening_stock,
SUM(s.soldQty) AS sold_qty,
MIN(s.remaining_qty) AS closing_stock,
s.date_created,
g.pcode,
g.qty,
g.received_qty,
g.received_on
FROM tbl_products p
LEFT JOIN tbl_sold_items s
ON p.pcode = s.pcode
LEFT JOIN tbl_shop_gr_items g
ON p.pcode = g.pcode
WHERE
(s.date_created = '2019-09-27') AND
(g.received_on = '2019-09-27')
GROUP BY p.pcode
stock_report_sample
When the above query is executed it return null values when one of the selected table doesn't have the item id for that particular day. I want it to show a list of all the items(products) available even though the item has not been sold or received so that in those instances it should show zero (0)
Maybe you can use ISNULL to show zero value if NULL
SELECT
p.pcode,
p.productName,
s.pcode,
ISNULL(MAX(s.in_stock),0) AS opening_stock,
ISNULL(SUM(s.soldQty),0) AS sold_qty,
ISNULL(MIN(s.remaining_qty),0) AS closing_stock,
s.date_created,
g.pcode,
g.qty,
g.received_qty,
g.received_on
FROM tbl_products p
LEFT JOIN tbl_sold_items s ON p.pcode = s.pcode
LEFT JOIN tbl_shop_gr_items g ON p.pcode = g.pcode
WHERE(s.date_created = '2019-09-27') AND (g.received_on = '2019-09-27')
GROUP BY p.pcode
SELECT
p.pcode,
p.productName,
CASE
WHEN gr_rows IS NULL AND sl_rows IS NULL THEN 0
WHEN gr_rows > 0 AND sl_rows IS NULL THEN received_stock
WHEN gr_rows > 0 AND sl_rows > 0 THEN opening_stock
ELSE 0
END AS op_stock,
IFNULL(received_stock, 0),IFNULL(sold_stock, 0)
FROM tbl_products p
LEFT JOIN (
SELECT COUNT(r.ID) AS gr_rows,r.pcode,r.received_on,SUM(r.received_qty) AS received_stock
FROM tbl_shop_gr_items r
WHERE r.received_on = '2019-10-03'
GROUP BY r.pcode
)AS r ON p.pcode = r.pcode
LEFT JOIN (
SELECT COUNT(s.ID) AS sl_rows,s.pcode,s.date_created,SUM(s.soldQty) AS sold_stock
FROM tbl_sold_items s
WHERE s.date_created = '2019-10-03'
GROUP BY s.pcode
)AS s ON p.pcode = s.pcode
LEFT JOIN (
SELECT t.ID,t.pcode,t.date_created,t.remaining_qty AS opening_stock
FROM tbl_sold_items t
WHERE t.date_created > '2019-10-03'
GROUP BY t.pcode ORDER BY t.ID
)AS t ON p.pcode = t.pcode
The above code has solved my issue

how to limit record in left join

SELECT commerce_product_field_data_commerce_product__field_data_field_products.entity_id, field_products_commerce_product.nid FROM commerce_order o
join commerce_payment_transaction t on o.order_id = t.order_id
join commerce_line_item i on o.order_id = i.order_id
LEFT JOIN field_data_commerce_total s ON i.line_item_id = s.entity_id AND (s.entity_type = 'commerce_line_item' AND s.deleted = '0')
LEFT JOIN field_data_commerce_product field_data_commerce_product ON i.line_item_id = field_data_commerce_product.entity_id AND (field_data_commerce_product.entity_type = 'commerce_line_item' AND field_data_commerce_product.deleted = '0')
INNER JOIN commerce_product commerce_product_field_data_commerce_product ON field_data_commerce_product.commerce_product_product_id = commerce_product_field_data_commerce_product.product_id
LEFT JOIN
(select * from field_data_field_products)
commerce_product_field_data_commerce_product__field_data_field_products ON commerce_product_field_data_commerce_product.product_id = commerce_product_field_data_commerce_product__field_data_field_products.field_products_product_id
LEFT JOIN ( select nid as nid from node order by nid)
field_products_commerce_product
ON commerce_product_field_data_commerce_product__field_data_field_products.entity_id = field_products_commerce_product.nid LEFT JOIN (
select r.entity_id, r.field_ranges_value from field_data_field_ranges r
) r
on r.entity_id = field_products_commerce_product.nid
WHERE t.status = 'success' and i.type = 'product' and o.Uid <> 0
AND o.status IN ('completed') and o.created >= '1483228800' and o.created <= '1483315200' and r.field_ranges_value = 'Tasty Sticks'
Is my sql
It is giving me 5 results. I only need 4
One of the product id's belong to two Drupal nodes and I only want one of them
I tried changing LEFT JOIN ( select nid as nid from node order by nid) to
LEFT JOIN ( select nid as nid from node order by nid limit 1) but then I don't get any records at all. Any idea what needs changing please other than removing one of the duplicate nodes. Thanks

invoice type fetch query from tables

ER diagram
ER diagram is attached
I need to get sales invoice invoices.type = 'sales' and invoices.type = 'purchase'
with company name as you can see in select statement
also sales and purchase columns
My query
SELECT jobs.id as jobID,
-- c.name AS Customer,jobs.job_no,
invoices.invoice_due_date,
jobs.id,
( (invoice_items.amount * invoice_items.quantity * invoice_items.exchange_rate )) as Ammount
FROM invoices
INNER JOIN `invoice_items` ON invoices.id = invoice_items.invoice_id
INNER JOIN `jobs` ON jobs.id = invoices.job_id
-- INNER JOIN `company` as c ON c.company_id = jobs.company_id -- jobs and company.
WHERE invoices.type = 'sales'
-- new conditions
AND MONTH(jobs.created_at) = '3'
AND YEAR(jobs.created_at) = '2017'
AND jobs.status > 0
AND jobs.complete_job > 0
AND jobs.completed_at IS NOT NULL
AND invoice_items.deleted_at IS NULL
GROUP BY jobs.job_no
ORDER BY invoices.invoice_due_date DESC
Try this updated...
SELECT jobs.id as jobID,
C.name AS Customer,jobs.job_no,
invoices.invoice_due_date,
jobs.id,
( (invoice_items.amount * invoice_items.quantity *invoice_items.exchange_rate )) as Ammount,
CASE invoices.type
WHEN 'sales' THEN 'S'
ELSE 'P'
END as trans_type
FROM invoices
INNER JOIN `invoice_items` ON invoices.id = invoice_items.invoice_id
INNER JOIN `jobs` ON jobs.id = invoices.job_id
LEFT OUTER JOIN `company` as C ON C.company_id = jobs.company_id
WHERE (invoices.type = 'sales' OR invoices.type = 'purchase') AND (MONTH(jobs.created_at) = '3') AND (YEAR(jobs.created_at) = '2017') AND (jobs.status > 0) AND (jobs.complete_job > 0) AND (jobs.completed_at IS NOT NULL)

How to create codeigniter query from below sql query?

I've a query like this which is working fine but I want to create a pure CI query from this. I'm new in CI so can anyone help me to figure out how this can be done or suggest me a reference website or link from where i can get help. Thanks
SELECT
user_des,
IFNULL((sent),0) as sent,
IFNULL((viewed),0) as viewed,
CONCAT(IFNULL(fname_usr,user_des),' ',lname_usr,user_des) as fullname,
IFNULL(sum(duration),0) as totalviewtime,
IFNULL((totalviews),0) as views,
IFNULL(sum(sharedcount),0) as shares,
IFNULL(sum(shared),0) as shared
FROM dem_senddemo
INNER JOIN
(SELECT * FROM dem_demos WHERE id_dem IN (746,943,748) AND customer_dem = '1') as demosfiltered
ON demo_des = id_dem
LEFT JOIN
(
(
Select senddemo_wis, sum(duration) as duration, max(datereceived_wis) as datereceived_wis
FROM
(
select senddemo_wis, invited_wis, sum(IFNULL(duration_fea,0) * IFNULL(percentviewed_wis,0)) as duration, max(datereceived_wis) as datereceived_wis
FROM (sta_views
LEFT JOIN sta_featureswisitavisits as s ON visit_fvi = id_vis
LEFT JOIN
(
(SELECT shortvideovid_fea as videoid_fea, shortvideoduration_fea as duration_fea
FROM dem_features
where shortvideoduration_fea > 0)
UNION
(SELECT longvideovid_fea as videoid_fea, longvideoduration_fea as duration_fea
FROM dem_features
where longvideoduration_fea > 0)
) as x
ON videoid_fea = showedvideo_fvi)
LEFT JOIN
sta_wistia as w ON invited_fvi = invited_wis AND s.showedvideo_fvi = w.mediaid_wis AND wistia_vis = email_wis
WHERE countvisit_wis <> 'N'
GROUP BY invited_wis
) as durfea
GROUP BY senddemo_wis
) UNION
(
SELECT senddemo_wis,sum(IFNULL(mainvideoduration_dem ,0) * IFNULL(percentviewed_wis,0)) as duration, max(datereceived_wis) as datereceived_wis
FROM sta_wistia as w
INNER JOIN
(select *, customer_dem as cuss FROM dem_demos) as demcorp ON demo_wis = id_dem AND mainmessagingvideovid_dem = w.mediaid_wis
LEFT JOIN sta_views ON email_wis = wistia_vis
WHERE customer_dem = 1 AND senddemo_wis > 0 AND countvisit_wis <> 'N'
GROUP BY senddemo_wis
)
) as c ON id_des = senddemo_wis
LEFT JOIN
(
SELECT user_des as user2_des, count(id_vis) as totalviews
FROM sta_views
LEFT JOIN dem_invited ON id_invited = invited_vis
LEFT JOIN dem_senddemo ON id_des = id_senddemo
WHERE NOT ISNULL(id_senddemo) AND countvisit_wis != 'N' AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND demo_des IN (746,943,748)
GROUP BY user_des
) as z ON user_des = user2_des
LEFT JOIN
(
SELECT user_des as user3_des, count(id_des) as sent
FROM dem_senddemo
LEFT JOIN dem_invited ON id_senddemo = id_des
WHERE createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND demo_des IN (746,943,748) AND first_invited = 'YES'
GROUP BY user_des
) as za ON user_des = user3_des
LEFT JOIN
(
SELECT user_des as user4_des, count(id_vis) as viewed
FROM sta_views LEFT JOIN dem_invited ON id_invited = invited_vis
LEFT JOIN dem_senddemo ON id_des = id_senddemo
WHERE NOT ISNULL(id_senddemo) AND countvisit_wis != 'N' AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND state = 'VIEWED'
AND first_invited = 'YES' AND demo_des IN (746,943,748)
GROUP BY user_des
) as zb ON user_des = user4_des
LEFT JOIN
(
SELECT id_senddemo as iddemdemos2, count(id_senddemo) as shared, allshares as sharedcount
FROM
(
SELECT id_senddemo, count(id_senddemo) as allshares
FROM dem_invited
LEFT JOIN dem_senddemo on id_senddemo = id_des
WHERE first_invited <> 'YES' AND demo_des IN (746,943,748)
GROUP BY id_senddemo
) as x
GROUP BY id_senddemo
) as zc ON iddemdemos2 = id_des
LEFT JOIN
sec_users ON user_des = id_usr
WHERE customer_dem = 1 AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59'
GROUP BY user_des