Join two MySQL SELECT statements containing one WHERE clause - mysql

How can I join the two select statements below to work as one statement? I would like the result to appear in one table. Thanks for your help.
First statement -
SELECT Account_ID, SUM(Profit_Loss) AS Starting_Balance
FROM client_ledger_history
WHERE Summary = 'Cash In'
GROUP BY Account_ID WITH ROLLUP
Second statement -
SELECT
client_ig_client_list.Account_ID,
client_ig_client_list.`Name`,
Share_Status,
Forex_Status,
Index_Status,
Share_Weighting,
Forex_Weighting,
Index_Weighting,
SUM(
client_ledger_history.Profit_Loss
) AS Current_Balance
FROM
client_ledger_history
LEFT JOIN client_ig_client_list ON client_ig_client_list.Account_ID = client_ledger_history.Account_ID
GROUP BY
Account_ID WITH ROLLUP

You should make a join into a nested table
SELECT
client_ig_client_list.Account_ID,
Starting_Balance,
client_ig_client_list.`Name`,
Share_Status,
Forex_Status,
Index_Status,
Share_Weighting,
Forex_Weighting,
Index_Weighting,
SUM(client_ledger_history.Profit_Loss) AS Current_Balance
FROM
client_ledger_history LEFT JOIN client_ig_client_list ON client_ig_client_list.Account_ID = client_ledger_history.Account_ID
LEFT JOIN
(SELECT Account_ID, SUM(Profit_Loss) AS Starting_Balance
FROM client_ledger_history WHERE Summary = 'Cash In' GROUP BY Account_ID WITH ROLLUP) as client_ledger_aggreagated_history
ON client_ledger_aggreagated_history.Account_ID = client_ledger_history.Account_ID
GROUP BY Account_ID WITH ROLLUP

Related

SELECT query take too much time to process

The following MySQL query take too much time. its take 24sec . and total records not more the 15000 each table please guide me for faster
Thanks
select c1.code,
( SELECT COALESCE(sum(i.total_amount),0)
FROM invoice as i
WHERE i.customer_code= c1.code
)-
( SELECT COALESCE(sum(p.amount),0)
FROM collection as p
where p.customer_code = c1.code
)-
( SELECT COALESCE(sum(CN.amount),0)
FROM cr_note as CN
where CN.customer_code= c1.code
) as rem_Balance
from customer as c1
you make it fast by replacing sub queries to queries with left joins like this:
WITH allInvoice AS (SELECT customer_code AS code, SUM(total_amount) AS amount FROM invoice GROUP BY customer_code),
allCollection AS (SELECT customer_code AS code, SUM(amount) AS amount FROM collection GROUP BY customer_code),
allNote AS (SELECT customer_code AS code, SUM(amount) AS amount FROM cr_note GROUP BY customer_code)
SELECT customer.code,
(COALESCE(allInvoice.amount) - COALESCE(allCollection.amount) - COALESCE(allNote.amount)) AS rem_Balance
FROM customer
LEFT JOIN allInvoice ON allInvoice.code = customer.code
LEFT JOIN allCollection ON allCollection.code = customer.code
LEFT JOIN allNote ON allNote.code = customer.code

How to Join the table in phpmyadmin

This is two query that i need to combine:
first query:
SELECT emp.name, count(rej.employee_ic) as 'rejected leave'
FROM employee as emp
LEFT OUTER JOIN rejectedleave as rej
ON emp.ic_no = rej.employee_ic
GROUP BY emp.`ic_no`
Second query:
SELECT emp.name, count(app.employee_ic) as 'approved leave'
FROM employee as emp
LEFT OUTER JOIN approvedleave as app
ON emp.ic_no = app.employee_ic
GROUP BY emp.`ic_no`
The output:
first query:
first query output image
second query:
second query output image
i want to combine this two table into one table. please help me to solve this problem, appreciate your help.
Is this you need? It find the count of approved and rejected leaves for each available employee in separate subqueries and then joins it with the employee table to show the count of rejected and approved leaves for each employee in one row.
Use coalesce(col,0) to return 0 if the count if null.
Coalesce returns first non null value from the given list of arguments.
select
t1.*,
coalesce(t2.approvedleave,0) approvedleave
coalesce(t3.rejectedleave,0) rejectedleave
from employee t1
left join (
select employee_ic, count(*) approvedleave
from approvedleave
group by employee_ic
) t2 on t1.ic_no = t2.employee_ic
left join (
select employee_ic, count(*) rejectedleave
from rejectedleave
group by employee_ic
) t3 on t1.ic_no = t3.employee_ic;
Read about coalesce here:
http://www.w3resource.com/mysql/comparision-functions-and-operators/coalesce-function.php
I suspect you want this:
SELECT e.name, COALESCE(r.rejected_leave, 0) as rejected_leave,
COALESCE(a.approved_leave, 0) as approved_leave
FROM employee e LEFT OUTER JOIN
(SELECT rl.employee_ic, COUNT(*) as rejected_leave
FROM rejectedleave rl
GROUP BY rl.employee_ic
) r
ON e.ic_no = r.employee_ic LEFT OUTER JOIN
(SELECT al.employee_ic, COUNT(*) as approved_leave
FROM approvedleave al
GROUP BY al.employee_ic
) a
ON e.ic_no = a.employee_ic;
That is, do the aggregation before doing the joins. This assumes that e.ic_no and e.name are both unique in the employees table.

can someone help me why this code fails at c_orders (c_custkey, c_count) when executed in Mysql

select c_count, count(*) as custdist
from
(
select c_custkey, count(o_orderkey)
from customer left outer join orders
on c_custkey = o_custkey and o_comment not like '%special%requests%'
group by c_custkey
) as c_orders (c_custkey, c_count)
group by c_count
order by custdist desc, c_count desc;
Try this query:
select c_orders.c_count, count(*) as custdist
from
(
select c_custkey, count(o_orderkey) as c_count
from customer left outer join orders
on c_custkey = o_custkey and o_comment not like '%special%requests%'
group by c_custkey
) as c_orders
group by c_orders.c_count
order by custdist desc, c_orders.c_count desc;
I saw two problems with your original query. First, you were referring to a column in your outer query which does not exist in the temporary table in your inner query:
select c_count, ...
But this column does not exist in the inner temporary table. Next, you had some strange syntax next to the alias for your temporary table:
) as c_orders (c_custkey, c_count)
You don't need whatever you had in parentheses, so I removed it.

LEFT JOIN SUM with WHERE clause

The following query always outputs SUM for all rows instead of per userid. Not sure where else to look. Please help.
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
) assignments ON (userid = assignments.userid AND ticketid = ?)
WHERE ticketid = ?
ORDER BY assigned,scheduled
If you want to keep the SELECT *, you would have to add a group by clause in the subquery. Something like this
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
GROUP BY userid
) time_entriesSummed ON time_entriesSummed.userid = assignments.userid
WHERE ticketid = ?
ORDER BY assigned,scheduled
But a better way would be to change the SELECT * to instead select the fields you want a add a group by clause directly. Something like this
SELECT
assignments.id,
assignments.assigned,
assignments.scheduled,
SUM(time_entries.timeworked) AS totalTimeworked
FROM assignments
LEFT JOIN time_entries
ON time_entries.userid = assignments.userid
GROUP BY assignments.id, assignments.assigned, assignments.scheduled
Edit 1
Included table names in query 2 as mentioned in chameera's comment below

Mysql Group BY with if statement

I'm not sure if this is something you can do in a single select statement without nesting selects.
I am grouping my results and I want to know IF a field inside the entire grouping contains a condition, display yes. With this it will just take the first row from the group and check the condition instead of all the rows in the group
if(field = 'condition','yes','no') as field_found
example table: id, score
SELECT t1.id, (
SELECT IF("10" IN (
SELECT score FROM table t2 WHERE t1.id = t2.id
),'yes','no'))
FROM table t1
GROUP BY t1.id
does that work?
Since you are already doing a group by, you should be able to add a MAX() as a column having the condition you are expecting and just add that to the group... such as
select
MAX( if( field LIKE '%condition%','1', '2' )) as ExtraOrderBy,
First_Name,
Last_Name,
... rest of query ...
group by
customers.Customer_ID
order by
1
In this case, the order by is the ordinal column in the SQL list instead of explicit retyping the MAX( IF() ) condition... So, if the condition is true, mark it with "1", otherwise "2" will float all those that qualify to the top of the list... Then, you could sub-order by other things like last name, first name, or other fields you have queried.
if(GROUP_CONCAT(field) LIKE '%condition%','yes','no')
SELECT first_name,last_name, CONCAT(physical_address," ",physical_address2," ",city, " ",zip) as address, MONTHNAME(install_date) as billing_month, IFNULL(status.quantity,0) as total_measures_instalclient2d,IFNULL(client1_measures,"") as client1_measures,IFNULL(client2_measures,"") as client2_measures,IFNULL(client1_quantity,0) as client1_quantity,IFNULL(client2_quantity,0) as client2_quantity,if(GROUP_CONCAT(measure_list.measure_type) LIKE '%Outreach/ Assessment%','yes','no') as outreach_invoiced,GROUP_CONCAT(IF(client='Client1',CONCAT(percent*100,"%-",measure_list.measure_type),NULL)) as client1_percent,GROUP_CONCAT(IF(client='Client2',CONCAT(percent*100,"%-",measure_list.measure_type),NULL)) as client2_percent,work_order.notes FROM customers
INNER JOIN measure on measure.customer_id = customers.customer_id
INNER JOIN measure_list on measure_list.measure_list_id = measure.measure_list_id
INNER JOIN work_order on work_order.work_order_id = measure.work_order_id
INNER JOIN billing on billing.workmanship = work_order.workmanship AND billing.measure_type = measure_list.measure_type
LEFT JOIN (
SELECT customers.customer_id,SUM(quantity) as quantity,GROUP_CONCAT(IF(client='Client1',measure_description,NULL)) as client1_measures,GROUP_CONCAT(IF(client='client2',measure_description,NULL)) as client2_measures,SUM(IF(client='client1',quantity,0)) as client1_quantity,SUM(IF(client='client2',quantity,0)) as client2_quantity FROM customers
INNER JOIN measure on measure.customer_id = customers.customer_id
INNER JOIN measure_list on measure_list.measure_list_id = measure.measure_list_id
INNER JOIN work_order on work_order.work_order_id = measure.work_order_id
INNER JOIN billing on billing.workmanship = work_order.workmanship AND billing.measure_type = measure_list.measure_type
WHERE measure_list.measure_type NOT IN ('measure1','measure2')
GROUP BY customers.customer_id
) as status on status.customer_id = customers.customer_id
WHERE measure_list.measure_type IN ('measure1','measure2')
GROUP BY customers.customer_id