Any way to reference MySQL "AS" values within the query? - mysql

in the following query, I sum up all the Sale Items of all the Sales in the given range. Included in this summary is "sumOfCost" and "sumOfPrice", I'd like "sumOfProfit" too. The problem is, as they're only "AS" variables, I'm not sure how to reference them, and my attempt of "... Blah AS blah, sumOfPrice - sumOfCost = sumOfProfit ..." sadly didn't work!
Here is my query:
SELECT Sales.SaleID,
Sales.StaffID,
Sales.CustomerID,
Sales.Timestamp,
Sales.Refunded,
Sales.PaymentType,
Staff.Forename AS staffForename,
Staff.Surname AS staffSurname,
(
SELECT GROUP_CONCAT(Quantity, ' x ', Name)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS itemList,
(
SELECT sum(Cost*Quantity)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS sumOfCost,
(
SELECT sum(Price*Quantity)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS sumOfPrice
FROM Sales
INNER JOIN Staff
ON Sales.StaffID = Staff.StaffID
WHERE Sales.Deleted = '0'
ORDER BY Timestamp DESC
LIMIT 0, 15
Apologies for the length of the query, I've struggled before to optimise it better but right now I'm only looking to solve this problem.
Thanks in advance :)

One alternative to solve this problem is by wrapping the whole query with a subquery,
SELECT *,
sumOfCost - sumOfPrice AS sumOfProfit
FROM
(
SELECT Sales.SaleID,
Sales.StaffID,
Sales.CustomerID,
Sales.Timestamp,
Sales.Refunded,
Sales.PaymentType,
Staff.Forename AS staffForename,
Staff.Surname AS staffSurname,
(
SELECT GROUP_CONCAT(Quantity, ' x ', Name)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS itemList,
(
SELECT sum(Cost*Quantity)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS sumOfCost,
(
SELECT sum(Price*Quantity)
FROM SaleItems
WHERE SaleItems.SaleID = Sales.SaleID
) AS sumOfPrice
FROM Sales
INNER JOIN Staff
ON Sales.StaffID = Staff.StaffID
WHERE Sales.Deleted = '0'
ORDER BY Timestamp DESC
LIMIT 0, 15
) s
By the way, they are called ALIAS.
The reason why ALIAS can't be used for calculation on the same level where they were defined is because the server executes the FROM clause before the SELECT clause. The ALIAS are on the SELECT clause, here's the full SQL Order of Operation:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
For better performance issue, I'll rather using JOIN than subqueries.
UPDATE 1
SELECT Sales.SaleID,
Sales.StaffID,
Sales.CustomerID,
Sales.Timestamp,
Sales.Refunded,
Sales.PaymentType,
Staff.Forename AS staffForename,
Staff.Surname AS staffSurname,
COALESCE(a.itemList, '') itemList,
COALESCE(b.sumOfCost, 0) sumOfCost,
COALESCE(c.sumOfPrice, 0) sumOfPrice,
COALESCE(b.sumOfCost, 0) - COALESCE(c.sumOfPrice, 0) AS sumOfProfit
FROM Sales
INNER JOIN Staff
ON Sales.StaffID = Staff.StaffID
LEFT JOIN
(
SELECT SaleID, GROUP_CONCAT(Quantity, ' x ', Name) itemList
FROM SaleItems
GROUP BY SaleID
) a ON a.SaleID = Sales.SaleID
LEFT JOIN
(
SELECT SaleID, sum(Cost*Quantity) sumOfCost
FROM SaleItems
GROUP BY SaleID
) b ON b.SaleID = Sales.SaleID
LEFT JOIN
(
SELECT SaleID, sum(Price*Quantity) sumOfPrice
FROM SaleItems
GROUP BY SaleID
) c ON c.SaleID = Sales.SaleID
WHERE Sales.Deleted = '0'
ORDER BY Timestamp DESC
LIMIT 0, 15
UPDATE 2
SELECT Sales.SaleID,
Sales.StaffID,
Sales.CustomerID,
Sales.TIMESTAMP,
Sales.Refunded,
Sales.PaymentType,
Staff.Forename AS staffForename,
Staff.Surname AS staffSurname,
COALESCE(a.itemList, '') itemList,
COALESCE(a.sumOfCost, 0) sumOfCost,
COALESCE(a.sumOfPrice, 0) sumOfPrice,
COALESCE(a.sumOfCost, 0) - COALESCE(a.sumOfPrice, 0) AS sumOfProfit
FROM Sales
INNER JOIN Staff
ON Sales.StaffID = Staff.StaffID
LEFT JOIN
(
SELECT SaleID,
GROUP_CONCAT(Quantity, ' x ', Name) itemList,
SUM(Cost*Quantity) sumOfCost,
SUM(Price*Quantity) sumOfPrice
FROM SaleItems
GROUP BY SaleID
) a ON a.SaleID = Sales.SaleID
WHERE Sales.Deleted = '0'
ORDER BY TIMESTAMP DESC
LIMIT 0, 15

Related

how can i modify my query to not create duplicates after i have introduce the order_activities table?

Usually when joining between two tables where there is a one-to-many relationship there will be duplicates created
Which i am joining with order-activities table
query = f"""
SELECT {time_period_column_name},
store_id,
st.name as store_name,
shopper_id,
first_names,
last_name,
total_orders,
total_items_picked,
shopper_request_time,
shopper_accepted_time,
shopping_completed_time,
ROUND(total_shopping_minutes, 2) as total_shopping_minutes,
ROUND(min_shopping_minutes, 2) AS min_shopping_minutes,
ROUND(max_shopping_minutes, 2) AS max_shopping_minutes,
ROUND(average_shopping_minutes, 2) as average_shopping_minutes,
ROUND(total_shopping_minutes / total_orders, 2) as minutes_per_order,
ROUND(total_items_picked / total_shopping_minutes, 2) as shopping_efficiency,
ROUND(average_order_zar, 2) as average_order_zar
FROM (
SELECT o.shopper_id,
o.store_id,
{time_period_column_name},
Count(1) AS total_orders,
TIMEDIFF(Max(o.shopper_request_stop), Max(o.shopper_request_start)) AS shopper_request_time,
TIMEDIFF(Max(o.shopper_accepted_stop), Max(o.shopper_accepted_start)) AS shopper_accepted_time,
TIMEDIFF(Max(o.shopping_completed_stop), Max(o.shopping_completed_start)) AS shopping_completed_time,
Sum(order_items_picked) AS total_items_picked,
AVG(o.total) / 100.0 AS average_order_zar,
Min(shopping_minutes) AS min_shopping_minutes,
Max(shopping_minutes) AS max_shopping_minutes,
Avg(shopping_minutes) AS average_shopping_minutes,
Sum(shopping_minutes) AS total_shopping_minutes
FROM (
SELECT oo.shopper_id,
oo.store_id,
oo.total,
order_item_counts.order_items_picked,
date_format(oo.created_at, '{time_period_format_str}') AS {time_period_column_name},
IF(oa.status_code = 'shopper-request', oa.created_at, NULL) AS shopper_request_start,
IF(oa.prev_status_code = 'shopper-request', oa.created_at, NULL) AS shopper_request_stop,
IF(oa.status_code = 'shopper-accepted', oa.created_at, NULL) AS shopper_accepted_start,
IF(oa.prev_status_code = 'shopper-accepted', oa.created_at, NULL) AS shopper_accepted_stop,
IF(oa.status_code = 'shopping-completed', oa.created_at, NULL) AS shopping_completed_start,
IF(oa.prev_status_code = 'shopping-completed', oa.created_at, NULL) AS shopping_completed_stop,
(TIMESTAMPDIFF(MICROSECOND, oo.started_shopping_at,
oo.finished_shopping_at) / 6E7) AS shopping_minutes
FROM {self.market_db}.orders as oo
LEFT JOIN (
SELECT order_id, Sum(picked) as order_items_picked FROM {self.market_db}.order_items oi
WHERE oi.store_id IN ({store_ids_str})
GROUP BY oi.order_id
) order_item_counts ON oo.id = order_item_counts.order_id
LEFT JOIN {self.market_db}.order_activities as oa ON oo.id = oa.order_id
WHERE (oa.prev_status_code IN ('shopper-request',
'shopper-accepted',
'shopping',
'shopping-completed',
'collected',
'delivery')
OR oa.status_code IN ('shopper-request',
'shopper-accepted',
'shopping',
'shopping-completed',
'collected',
'delivery'))
AND oa.created_at >= '{start_date}'
AND oa.created_at < '{end_date}'
AND oo.started_shopping_at IS NOT NULL
AND oo.finished_shopping_at IS NOT NULL
AND oa.status_code <> oa.prev_status_code
AND oo.store_id IN ({store_ids_str})
) AS o
GROUP BY shopper_id, {time_period_column_name}, store_id
HAVING total_orders >= 1
) AS oc
INNER JOIN {self.users_db}.users us
ON us.id = oc.shopper_id
INNER JOIN {self.market_db}.stores st
ON st.id = oc.store_id
ORDER BY store_id DESC, {time_period_column_name} DESC, total_orders DESC;
"""
rows = self.run_market_query(query=query)
return rows

MySQL where condition based on select query

I am having the following query to fetch the data from the table.
SELECT rental_plans.*,
( ( inventory.total_inventory
+ vehicles.tmp_qty ) - Ifnull(reservation.total_reserved, 0) ) AS
vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN (SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN (SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE ( '2018-12-18' BETWEEN pickup_date AND drop_date )
OR ( '2018-12-28' BETWEEN pickup_date AND drop_date )
AND `status` NOT IN ( 'RETURNED' )
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` = `reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10'
ORDER BY `rental_plans`.`price` ASC
But I want to handle where condition based on vehicle_inventory.
I tried with ... AND vehicle_inventory > 16 order by `rental_plans`.`price` ASC but this generates the error that column not found in the table
The reason is that vehicle_inventory is an alias and it is resolved after WHERE clause. You can read about that here. You can do something like:
SELECT *
FROM (SELECT rental_plans.*,
( ( inventory.total_inventory
+ vehicles.tmp_qty ) - Ifnull(reservation.total_reserved, 0)
) AS
vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN (SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN (SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE ( '2018-12-18' BETWEEN
pickup_date AND drop_date )
OR ( '2018-12-28' BETWEEN
pickup_date AND drop_date )
AND `status` NOT IN ( 'RETURNED' )
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` =
`reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10')a
WHERE a.rental_plans > 16
ORDER BY `price` ASC
or
SELECT rental_plans.*,
( (inventory.total_inventory + vehicles.tmp_qty) - Ifnull(reservation.total_reserved, 0) ) AS vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN
(
SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN
(
SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE (
'2018-12-18' BETWEEN pickup_date AND drop_date)
OR (
'2018-12-28' BETWEEN pickup_date AND drop_date)
AND `status` NOT IN ('RETURNED')
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` = `reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10'
where (
inventory.total_inventory + vehicles.tmp_qty) - ifnull(reservation.total_reserved, 0) > 16
ORDER BY `rental_plans`.`price` ASC

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

MySQL: Grouped by hour, need to show all hours, null where no data

Here's the query:
SELECT h.idhour, h.`hour`, outnumber, count(*) as `count`, sum(talktime) as `duration`
FROM (
SELECT
`cdrs`.`dcustomer` AS `dcustomer`,
(CASE
WHEN (`cdrs`.`cnumber` like "02%") THEN '02'
WHEN (`cdrs`.`cnumber` like "05%") THEN '05'
END) AS `outnumber`,
FROM_UNIXTIME(`cdrs`.`start`) AS `start`,
(`cdrs`.`end` - `cdrs`.`start`) AS `duration`,
`cdrs`.`talktime` AS `talktime`
FROM `cdrs`
WHERE `cdrs`.`start` >= #_START and `cdrs`.`start` < #_END
AND `cdrs`.`dtype` = _LATIN1'external'
GROUP BY callid
) cdr
JOIN customers c ON c.id = cdr.dcustomer
LEFT JOIN hub.hours h ON HOUR(cdr.`start`) = h.idhour
WHERE (c.parent = _ID or cdr.dcustomer = _ID or c.parent IN
(SELECT id FROM customers WHERE parent = _ID))
GROUP BY h.idhour, cdr.outnumber
ORDER BY h.idhour;
The above query results skips the hours where there is no data, but I need to show all hours (00:00 to 23:00) with null or 0 values. How can I do this?
SELECT h.idhour
, h.hour
,IFNULL(outnumber,'') AS outnumber
,IFNULL(cdr2.duration,0) AS duration
,IFNULL(output_count,0) AS output_count
FROM hub.hours h
LEFT JOIN (
SELECT HOUR(start) AS start,outnumber, SUM(talktime) as duration ,COUNT(1) AS output_count
FROM
(
SELECT cdrs.dcustomer AS dcustomer
, (CASE WHEN (cdrs.cnumber like "02%") THEN '02' WHEN (cdrs.cnumber like "05%") THEN '05' END) AS outnumber
, FROM_UNIXTIME(cdrs.start) AS start
, (cdrs.end - cdrs.start) AS duration
, cdrs.talktime AS talktime
FROM cdrs cdrs
INNER JOIN customers c ON c.id = cdrs.dcustomer
WHERE cdrs.start >= #_START and cdrs.start < #_END AND cdrs.dtype = _LATIN1'external'
AND
(c.parent = _ID or cdrs.dcustomer = _ID or c.parent IN (SELECT id FROM customers WHERE parent = _ID))
GROUP BY callid
) cdr
GROUP BY HOUR(start),outnumber
) cdr2
ON cdr2.start = h.idhour
ORDER BY h.idhour
You need a table with all hours, nothing else.
Then use LEFT JOIN with the hours table on the "left" and your current query on the "right":
SELECT b.*
FROM hours h
LEFT JOIN ( ... ) b ON b.hr = h.hr
WHERE h.hr BETWEEN ... AND ...
ORDER BY hr;
Any missing hours will be NULLs in b.*.

How to join 2 queries

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