Speed up query on mysql view - mysql

I have a very long query with multiple sub queries and this query can take up to 30 sec to complete.
Is there a better way to construct the query?
select FROM_UNIXTIME(peg_remedy_incident.PEG_OutageStartTime,"%m-%d-%Y") AS 'Incident Date', PEG_Category AS Category, (select GROUP_CONCAT(DISTINCT peg_frm_inc_incidentXnetworkRe.Market ORDER BY Market) from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types IN (1,2) GROUP BY peg_frm_inc_incidentXnetworkRe.IncidentVisibleID, peg_frm_inc_incidentXnetworkRe.CustomerCode) AS Market,peg_frm_inc_incidentXcustomerR.CustomerName AS 'Customer' , peg_frm_inc_incidentXcustomerR.CustomerTicket AS 'Customer TT#', peg_remedy_incident.PEG_NetworkProvider AS 'Network Provider', peg_remedy_incident.PEG_ProviderTicketNumber AS 'Network Provider TT#',
peg_remedy_incident.PEG_ThirdPartyVendor AS '3rd Party Support Vendor', peg_remedy_incident.PEG_ThirdPartyVendor_TT_ AS '3rd Party TT#','' AS 'Maintenance Window Outage? (Y/N)', TRIM(LEADING '0' FROM peg_frm_inc_incidentXcustomerR.IncidentID) AS 'TT#',FROM_UNIXTIME(peg_remedy_incident.PEG_OutageStartTime,"%m-%d-%Y %r") AS `Event Start Time`, FROM_UNIXTIME(peg_remedy_incident.PEG_OutageStopTime,"%m-%d-%Y %r") AS `Event Stop Time`,
'=(M{ROWID}-L{ROWID})*1440' AS 'Total Minutes', '=(M{ROWID}-L{ROWID})' AS 'Total Hours/Minutes','=(M{ROWID}-L{ROWID})*R{ROWID}*1440' AS ' Total Outage Minutes','=(M{ROWID}-L{ROWID})*R{ROWID}' AS ' Total Outage Hours/Minutes',
(select count(DISTINCT(Site_ID)) from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types=1) AS 'Outage Sites Impacted',
(select count(DISTINCT(Circuit_ID)) from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND
peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types=1) AS 'Outage Circuits Impacted',
(select count(DISTINCT(Site_ID)) from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types=2) AS 'Simplex Sites Impacted',
(select count(DISTINCT(Circuit_ID)) from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND
peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types=2) AS 'Simplex Circuits Impacted',
peg_remedy_incident.PEG_TechName AS 'Technician Dispatch', '' AS 'Summary & Ticket Notes', peg_remedy_incident.PEG_NetworkAvailabilityAffecti ,
CAST( CASE
WHEN peg_remedy_incident.PEG_Ring_Lateral = 'Lateral'
THEN 'Yes'
WHEN peg_remedy_incident.PEG_Ring_Lateral = 'Ring'
THEN 'No'
ELSE ''
END AS char(3)) as 'Lateral (Y/N)' ,
'' AS 'Backhaul/Non-Backhaul?', PEG_Resolution_Details AS 'Resolution Details',
PEG_CauseCode1 AS 'Cause Code 1', PEG_CauseCode2 AS 'Cause Code 2',
PEG_CauseCode3 AS 'Cause Code 3', PEG_CauseCode4 AS 'Cause Code 4', Root_Cause_Analysis AS 'Root Cause Analysis','' AS 'Notes',
(select GROUP_CONCAT(DISTINCT peg_frm_inc_incidentXwork_log.Notes ORDER BY Request_ID) AS 'Work Log1' from peg_frm_inc_incidentXwork_log WHERE peg_frm_inc_incidentXwork_log.Incident_ID=peg_frm_inc_incidentXcustomerR.IncidentID GROUP BY peg_frm_inc_incidentXwork_log.Incident_ID) as 'Work Log',
(select GROUP_CONCAT(DISTINCT peg_frm_inc_incidentXnetworkRe.Site_ID ORDER BY Site_ID) AS 'OutageSite List1' from peg_frm_inc_incidentXnetworkRe WHERE peg_frm_inc_incidentXnetworkRe.IncidentVisibleID=peg_frm_inc_incidentXcustomerR.IncidentID AND peg_frm_inc_incidentXcustomerR.CustomerCode=peg_frm_inc_incidentXnetworkRe.CustomerCode AND peg_frm_inc_incidentXnetworkRe.RadioButton_Types=1 GROUP BY peg_frm_inc_incidentXnetworkRe.IncidentVisibleID, peg_frm_inc_incidentXnetworkRe.CustomerCode) as 'Outage Site List'
FROM peg_frm_inc_incidentXcustomerR LEFT JOIN peg_frm_inc_incidentXnetworkRe ON peg_frm_inc_incidentXcustomerR.IncidentID=peg_frm_inc_incidentXnetworkRe.IncidentVisibleID
LEFT JOIN peg_remedy_incident ON peg_frm_inc_incidentXcustomerR.IncidentID=peg_remedy_incident.PEG_VisibleTicketID WHERE peg_frm_inc_incidentXnetworkRe.RadioButton_Types IN(1 ,2) AND peg_remedy_incident.PEG_VisibleTicketID>=000000000034000 GROUP BY peg_frm_inc_incidentXnetworkRe.IncidentVisibleID,peg_frm_inc_incidentXcustomerR.CustomerCode

Related

How to list order items with order total per item

I have two tables: booking and order_items where booking has many order_items. I need to create a query where I list all order_items group by booking id but in each item line I need to show the total of the booking (for instance, booking id 1 has 2 order_items costing £10 each so I need the query to show:)
item 1 name price (£10) discount booking total (in this case £20)
I have the following query:
SELECT
b.partner_order_id,
'Store Name' as 'Store',
CONCAT_WS(' ', b.customer_firstname, b.customer_lastname) AS 'Name',
'1' as 'Quantity',
oi.order_price as 'Price',
oi.discount as 'Discount',
SUM(order_price - discount) as 'Payment',
'0' as 'Shipping',
'Sale' as 'Transaction',
oi.order_sku as 'SKU',
oi.order_name as 'Description',
oi.order_color as 'Colour',
oi.order_size as 'Size'
FROM booking AS b
JOIN order_items oi on b.booking_id = oi.booking_id
WHERE
b.delivery_date >= DATE(NOW()) - INTERVAL 8 DAY and
b.partner_id = 36 and
oi.item_accepted = 1
GROUP BY oi.id
Which does almost everything I need apart from giving me the total per booking on each item line. Any ideas?
you need to add a sub query to your select like this:
SELECT
b.partner_order_id,
'Store Name' as 'Store',
CONCAT_WS(' ', b.customer_firstname, b.customer_lastname) AS 'Name',
'1' as 'Quantity',
oi.order_price as 'Price',
oi.discount as 'Discount',
SUM(order_price - discount) as 'Payment',
'0' as 'Shipping',
'Sale' as 'Transaction',
oi.order_sku as 'SKU',
oi.order_name as 'Description',
oi.order_color as 'Colour',
oi.order_size as 'Size',
(SELECT SUM(order_price) FROM order_items WHERE booking_id = b.booking_id) AS total
FROM booking AS b
JOIN order_items oi on b.booking_id = oi.booking_id
WHERE
b.delivery_date >= DATE(NOW()) - INTERVAL 8 DAY and
b.partner_id = 36 and
oi.item_accepted = 1
GROUP BY oi.id

MySQL subquery - using alias from SELECT in WHERE conditions (no CTE)

I'm trying to find out where/how to implement subquery in below trimmed down example.
The issue is that I need to add hours depending on time zones and then return those fields.
At the same time though, I need to filter by the same fields, and for it to be accurate, I need them to already be adjusted to the correct time zone.
Can you please give me an advice on how I can work this out?
SELECT
od.ID AS 'Id',
CASE WHEN tzp.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredStartTime, INTERVAL 1 HOUR)
ELSE od.declaredStartTime END AS 'Collection date\\time',
CASE WHEN tzd.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredEndTime, INTERVAL 1 HOUR)
ELSE od.declaredEndTime END AS 'Delivery date\\time'
FROM orders od
LEFT OUTER JOIN time_zone AS tzp
ON (tzp.ID = od.pickupTimeZone_ID)
LEFT OUTER JOIN time_zone AS tzd
ON (tzd.ID = od.dropTimeZone_ID)
WHERE
od.IS_DELETED != '1'
-- AND 'Delivery date\\time' >= '2019-06-30' --<< This won't work because
-- AND 'Delivery date\\time' <= '2019-08-01' --<< SELECT is the last operation
I unfortunately have no option to use CTE, as our MySQL is 5.6 and CTE is apparently available from 8.0
Edited: to make the code sample valid
Edit: full working version of the command
SELECT
od.ID AS 'Id',
od.referenceNumber AS 'Reference number',
od.secondReferenceNumber AS 'Second reference number',
od.status AS 'Status',
ADDDATE(od.created, INTERVAL 1 HOUR) AS 'Creation date/time', -- BST not accounted for!
st.name AS 'Shipment type',
IFNULL(sp.name, '') AS 'Supplier',
ls.name AS 'Collection location',
CASE WHEN tzp.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredStartTime, INTERVAL 1 HOUR)
ELSE od.declaredStartTime END AS 'Collection date\\time',
ld.name AS 'Delivery location',
CASE WHEN tzd.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredEndTime, INTERVAL 1 HOUR)
ELSE od.declaredEndTime END AS 'Delivery date\\time',
od.supplierRate AS 'Supplier rate (pounds)',
IFNULL(od.alternativeSupplierRate, '') AS 'Supplier alternative rate (pounds)',
od.supplierTransportTotal AS 'Supplier total rate (pounds)',
od.customerRate AS 'Customer rate (pounds)',
IFNULL(od.alternativeCustomerRate, '') AS 'Customer alternative rate (pounds)',
od.customerTransportTotal AS 'Customer total rate (pounds)',
IFNULL(od.quantity, '') AS 'Quantity',
IFNULL(od.weight, '') AS 'Weight',
IFNULL(od.palletQuantity, '') AS 'Pallet quantity',
IFNULL(od.kmsTravelled, '') AS 'Kms travelled',
IFNULL(od.carbonFootprint, '') AS 'Carbon footprint',
IFNULL(od.performanceScore, '') AS 'Performance score',
od.fuel_surcharge AS 'Fuel surcharge (pounds)',
od.caf_surcharge AS 'CAF surcharge (pounds)',
IFNULL(od.supplierFuelSurcharge, '') AS 'Supplier fuel surcharge (pounds)',
IFNULL(od.supplierCAFSurcharge, '') AS 'Supplier CAF surcharge (pounds)',
od.vehiclesRegistrationInformation AS 'Vehicles registration information',
od.trailerIsChecked AS 'Trailer is checked',
od.checkedTrailerNumber AS 'Trailer number',
od.additionalPickupsNumber AS 'Number of additional pickups',
od.additionalDropsNumber AS 'Number of additional drops',
IFNULL(od.customerRateFromPricingMatrix, '') AS 'Customer rate from pricing matrix',
IFNULL(od.supplierRateFromPricingMatrix, '') AS 'Supplier rate from pricing matrix',
IF(el.shipmentLateType IS NULL, 'FALSE', 'TRUE') AS 'Is late', -- NULL or late type
IFNULL(rc.name, '') AS 'Late category',
od.comment AS 'Comments',
od.customerComment AS 'Customer comments',
od.supplierComment AS 'Supplier comments',
IF(od.rejectedByCustomer, 'TRUE', 'FALSE') AS 'Rejected by customer', -- dbck
IFNULL(uc.name, '') AS 'Unallocation reason',
IFNULL(us2.name, '') AS 'Unallocation user',
IFNULL(ur.created, '') AS 'Unallocation date/time',
IFNULL(sp2.name, '') AS 'Unallocation supplier',
IFNULL(od.supplierRankPosition, '') AS 'Supplier\'s position',
IFNULL(od.supplierRank, '') AS 'Supplier\'s rank',
IFNULL(od.highestRankOnAllocation, '') AS 'Highest rank',
IF(od.proveOfDelivery IS NULL, 'FALSE', 'TRUE') AS 'POD attached', -- NULL or filename
IFNULL(od.supplierInvoiceNumber, '') AS 'Supplier Sage invoice number',
IFNULL(od.customerInvoiceNumber, '') AS 'Customer Sage invoice number',
IFNULL(od.purchaseOrderNumber, '') AS 'Purchase orders batch number',
IFNULL(vc.name, '') AS 'Vehicle',
IFNULL(od.invoicingKmsTravelled, '0') AS 'Actual Kms travelled',
IFNULL(od.duration, '0') AS 'Actual duration',
IFNULL(vc.location, '') AS 'Vehicle location', -- loc verify
IFNULL(tp.idling, '0') AS 'Idling time',
IFNULL(tp.fuelUsed, '0') AS 'Fuel used',
IF(od.hasDeliveryDiscrepancy, 'TRUE', 'FALSE') AS 'Has delivery discrepancy',
IFNULL(od.deliveryDiscrepancyReasonID, '') AS 'Delivery discrepancy reason Id',
IFNULL(dc1.title, '') AS 'Delivery discrepancy reason name',
IFNULL(od.deliveryDiscrepancyComment, '') AS 'Delivery discrepancy comment',
IF(od.hasHazardousGoods, 'TRUE', 'FALSE') AS 'Has hazardous goods',
IFNULL(od.surchargeReasonId, '') AS 'Surcharge reason Id',
IFNULL(dc2.title, '') AS 'Surcharge reason name',
od.bookingReference AS 'Booking reference',
od.driverName AS 'Driver',
CASE
WHEN ISNULL(wr.passed) THEN 'Not started'
WHEN SUM(CASE WHEN wr.passed=0 THEN 1 ELSE 0 END)=0
THEN 'Passed'
ELSE 'Failed'
END AS 'Walkaround Check status',
SUM(CASE
WHEN wr.passed=0 THEN 1 ELSE 0
END) AS 'Walkaround Check failed count'
FROM orders od
LEFT OUTER JOIN shipment_type AS st
ON (st.ID = od.shipmentType_ID)
LEFT OUTER JOIN shipment_unallocate_reason AS ur
ON (ur.shipment_ID = od.ID)
LEFT OUTER JOIN unallocate_reason_codes AS uc
ON (uc.ID = ur.reasonCode_ID)
LEFT OUTER JOIN user AS us2
ON (us2.ID = ur.user_ID)
LEFT OUTER JOIN suppliers AS sp
ON (sp.ID = od.supplier_ID)
LEFT OUTER JOIN suppliers AS sp2
ON (sp2.ID = ur.supplier_ID)
LEFT OUTER JOIN walk_around_check AS wc
ON (wc.shipment_id = od.ID)
LEFT OUTER JOIN walk_around_check_result AS wr
ON (wr.check_id = wc.ID)
LEFT OUTER JOIN walk_around_check_item AS wi
ON (wr.check_item_id = wi.id)
LEFT OUTER JOIN landmark AS ld
ON (ld.ID = od.destination_id)
LEFT OUTER JOIN landmark AS ls
ON (ls.ID = od.source_id)
LEFT OUTER JOIN landmark AS lw
ON (lw.ID = wc.location_id)
LEFT OUTER JOIN time_zone AS tzp
ON (tzp.ID = od.pickupTimeZone_ID)
LEFT OUTER JOIN time_zone AS tzd
ON (tzd.ID = od.dropTimeZone_ID)
LEFT OUTER JOIN user AS us
ON (us.ID = wc.driver_id)
LEFT OUTER JOIN shipment_event AS el
ON (el.Shipment_ID = od.ID) -- AND se.shipmentLateType = 'DELIVERY_LATE'
LEFT OUTER JOIN late_reason_codes AS rc
ON (rc.ID = el.reasonCode_ID)
LEFT OUTER JOIN dictionary AS dc1
ON (dc1.id = od.deliveryDiscrepancyReasonID)
LEFT OUTER JOIN dictionary AS dc2
ON (dc2.id = od.surchargeReasonId)
LEFT OUTER JOIN trips AS tp
ON (tp.shipment_ID = od.ID)
LEFT OUTER JOIN vehicle AS vc
ON (vc.id = tp.vehicle_ID)
WHERE od.IS_DELETED != '1'
-- NOTE: Have to compare dates incl. timezone changes!!!
-- AND 'Collection date\\time' >= '2019-06-30'
-- AND 'Collection date\\time' <= '2019-08-01'
-- AND 'Delivery date\\time' >= '2019-06-30'
-- AND 'Delivery date\\time' <= '2019-08-01'
GROUP BY od.ID -- required in conjunction with SUM to not return single row
ORDER BY od.ID ASC
You must repeat the CASE statement in the WHERE clause:
AND CASE
WHEN tzd.ZoneId='Etc/GMT-1'THEN ADDDATE(od.declaredEndTime, INTERVAL 1 HOUR)
ELSE od.declaredEndTime
END BETWEEN '2019-06-30' AND '2019-08-01'
instead of:
AND 'Delivery date\\time' >= '2019-06-30'
AND 'Delivery date\\time' <= '2019-08-01'
Another way of doing this is using a HAVING clause instead of WHERE but this would need to nest your query as a subquery because you already use GROUP BY:
SELECT Id, `Collection date\\time`, `Delivery date\\time`
FROM (
SELECT
od.ID AS 'Id',
CASE WHEN tzp.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredStartTime, INTERVAL 1 HOUR)
ELSE od.declaredStartTime END AS `Collection date\\time`,
CASE WHEN tzd.ZoneId='Etc/GMT-1'
THEN ADDDATE(od.declaredEndTime, INTERVAL 1 HOUR)
ELSE od.declaredEndTime END AS `Delivery date\\time`,
FROM orders od
LEFT OUTER JOIN time_zone AS tzp
ON (tzp.ID = od.pickupTimeZone_ID)
LEFT OUTER JOIN time_zone AS tzd
ON (tzd.ID = od.dropTimeZone_ID)
HAVING
od.IS_DELETED != '1'
AND `Delivery date\\time` >= '2019-06-30' --<< This won't work because
AND `Delivery date\\time` <= '2019-08-01' --<< SELECT is the last operation
)
GROUP....
Note: since you use the GROUP BY clause what is the point of these calculated columns in the select list? Your statement should not even run. Or maybe it's not the exact code you really have.

MySQL - Slow Query when adding multiple derived tables - Optimization

For my query, the two derived tables at the bottom are causing a crazy slow up for this query. The query, as is, takes about 45-55 seconds to execute.. NOW, when i remove just one of those derived tables (it does not matter which one) the query goes down to 0.1 - 0.3 seconds. My questions; Is there an issue with having multiple derived tables? Is there a better way to execute this? My indexes all seem to be correct, I will also include the explain from this query.
select t.name as team, u.name as "REP NAME",
count(distinct activity.id) as "TOTAL VISITS",
count(distinct activity.account_id) as "UNIQUE VISITS",
count(distinct placement.id) as "COMMITMENTS ADDED",
CASE WHEN
count(distinct activity.account_id) = 0 THEN (count(distinct
placement.id) / 1)
else (cast(count(distinct placement.id) as decimal(10,2)) /
cast(count(distinct activity.account_id) as decimal(10,2)))
end as "UNIQUE VISIT TO COMMITMENT %",
case when o.mode='basic' then count(distinct placement.id) else
count(distinct(case when placement.commitmentstatus='fullfilled'
then placement.id else 0 end))
end as "COMMITMENTS FULFILLED",
case when o.mode='basic' then 1 else
(CASE WHEN
count(distinct placement.id) = 0 THEN (count(distinct(case when
placement.commitmentstatus='fullfilled' then placement.id else 0
end)) / 1)
else (cast(count(distinct(case when
placement.commitmentstatus='fullfilled' then placement.id else 0
end)) as decimal(10,2)) / cast(count(distinct placement.id) as
decimal(10,2)))
end) end as "COMMITMENT TO FULFILLMENT %"
from lpmysqldb.users u
left join lpmysqldb.teams t on t.team_id=u.team_id
left join lpmysqldb.organizations o on o.id=t.org_id
left join (select * from lpmysqldb.activity where
org_id='555b918ae4b07b6ac5050852' and completed_at>='2018-05-01' and
completed_at<='2018-06-01' and tag='visit' and accountname is not
null and (status='active' or status='true' or status='1')) as
activity on activity.user_id=u.id
left join (select * from lpmysqldb.placements where
orgid='555b918ae4b07b6ac5050852' and placementdate>='2018-05-01' and
placementdate<='2018-06-01' and (status IN ('1','active','true') or
status is null)) as placement on placement.userid=u.id
where u.org_id='555b918ae4b07b6ac5050852'
and (u.status='active' or u.status='true' or u.status='1')
and istestuser!='1'
group by u.org_id, t.name, u.id, u.name, o.mode
order by count(distinct activity.id) desc
Thank you for assistance!
I have edited below with changing the two bottom joins from joining on subqueries to joining on the table directly. Still yielding the same result.
This is a SLIGHTLY restructured query of your same. Might be simplified as the last two subqueries are all pre-aggregated for your respective counts and count distincts so you can use those column names directly instead of showing all the count( distinct ) embedded throughout the query.
I also tried to simplify the division by multiplying a given count by 1.00 to force decimal-based precision as result.
select
t.name as team,
u.name as "REP NAME",
Activity.DistIdCnt as "TOTAL VISITS",
Activity.UniqAccountCnt as "UNIQUE VISITS",
Placement.DistIdCnt as "COMMITMENTS ADDED",
Placement.DistIdCnt /
CASE WHEN Activity.UniqAccountCnt = 0
THEN 1.00
ELSE Activity.UniqAccountCnt * 1.00
end as "UNIQUE VISIT TO COMMITMENT %",
case when o.mode = 'basic'
then Placement.DistIdCnt
else Placement.DistFulfillCnt
end as "COMMITMENTS FULFILLED",
case when o.mode = 'basic'
then 1
else ( Placement.DistFulfillCnt /
CASE when Placement.DistIdCnt = 0
then 1.00
ELSE Placement.DistIdCnt * 1.00
END TRANSACTION )
END as "COMMITMENT TO FULFILLMENT %"
from
lpmysqldb.users u
left join lpmysqldb.teams t
on u.team_id = t.team_id
left join lpmysqldb.organizations o
on t.org_id = o.id
left join
( select
user_id,
count(*) as AllRecs,
count( distinct id ) DistIdCnt,
count( distinct account_id) as UniqAccountCnt
from
lpmysqldb.activity
where
org_id = '555b918ae4b07b6ac5050852'
and completed_at>='2018-05-01'
and completed_at<='2018-06-01'
and tag='visit'
and accountname is not null
and status IN ( '1', 'active', 'true')
group by
user_id ) activity
on u.id = activity.user_id
left join
( select
userid,
count(*) AllRecs,
count(distinct id) as DistIdCnt,
count(distinct( case when commitmentstatus = 'fullfilled'
then id
else 0 end )) DistFulfillCnt
from
lpmysqldb.placements
where
orgid = '555b918ae4b07b6ac5050852'
and placementdate >= '2018-05-01'
and placementdate <= '2018-06-01'
and ( status is null OR status IN ('1','active','true')
group by
userid ) as placement
on u.id = placement.userid
where
u.org_id = '555b918ae4b07b6ac5050852'
and u.status IN ( 'active', 'true', '1')
and istestuser != '1'
group by
u.org_id,
t.name,
u.id,
u.name,
o.mode
order by
activity.DistIdCnt desc
FINALLY, your inner queries are querying for ALL users. If you have a large count of users that are NOT active, you MIGHT exclude those users from each inner query by adding those join/criteria there too such as...
( ...
from
lpmysqldb.placements
JOIN lpmysqldb.users u2
on placements.userid = u2.id
and u2.status IN ( 'active', 'true', '1')
and u2.istestuser != '1'
where … ) as placement

SQL sum inside the value

i have this kind of result but i want to sum up some of the value inside the value. Sorry for my english. Refer image for better understanding.
Expected Result:
My sql query :
SELECT
itmnocate.Source as Local,
itmnocate.GradeCategory,
sum(sales_data.QUANTITY/1000) AS UnitMT
FROM
sales_data
INNER JOIN itmnocate
ON sales_data.ITEM = itmnocate.ItemNumber
WHERE
sales_data.unit = 'KG'
AND
sales_data.CUSTOMERACCOUNT not in ('CT1008','CT1009')
AND itmnocate.Source in ('local','by product')
GROUP BY itmnocate.GradeCategory
WITH your_query
AS (SELECT 'BY PRODUCT' AS local,
'BY PRODUCT' AS "GradeCategory 1",
3380.59 AS unitmt
UNION ALL
SELECT 'LOCAL' AS local,
'LOCAL OTHERS' AS "GradeCategory 1",
2754.19 AS unitmt
UNION ALL
SELECT 'LOCAL' AS local,
'SUPER 15' AS "GradeCategory 1",
19598.17 AS unitmt
UNION ALL
SELECT 'LOCAL' AS local,
'TENDER/RAMPASAN' AS "GradeCategory 1",
53.65 AS unitmt
)
select MAX(local), sub_category,SUM(unitmt) from (SELECT local,
"GradeCategory 1",
unitmt,
CASE "GradeCategory 1" WHEN 'SUPER 15' THEN 'SUPER 15' ELSE 'LOCAL
OTHERS' END
AS sub_category
FROM your_query) processd_data group by sub_category
You can do what you want using a CASE expression to calculate the new category values:
SELECT 'LOCAL' as Local,
(CASE WHEN i.GradeCategory = 'SUPER 15' THEN 'SUPER 15'
ELSE 'OTHERS'
END) as Cat,
SUM(s.QUANTITY/1000) AS UnitMT
FROM sales_data s INNER JOIN
itmnocate i
ON s.ITEM = i.ItemNumber
WHERE s.unit = 'KG' AND
s.CUSTOMERACCOUNT NOT IN ('CT1008', 'CT1009') AND
i.Source in ('local', 'by product')
GROUP BY cat;

YII2 SQL: Get count of column with condition

I want to get the sum of li_units_bought for rows based on li_order_id.
I am joining multiple tables for it. Here is my query:
$query = (new \yii\db\Query())
->select('oid, ord_tracking_no as `Tracking No`, site_name as Region,adv_name as Advertiser, line_id as LineId, li_name as LineName
, li_status as StatusCode, prd_desc as Product, li_version as Version, date_format(lrh_updated_date,"%Y-%m-%d %H:%i") as `Submit Date`
, date_format(li_start_date,"%Y-%m-%d %H:%i") as `Start Date`
, date_format(li_end_date,"%Y-%m-%d %H:%i") as `End Date`, li_is_rush as isRushOrder
, li_type as Type, ord_assigned_user as `Assigned User`, status_desc as Status
, SUM(`li_units_bought`) as Goal
, ldp_total_delivery as `Delivered`
, if(li_type="STANDARD",((ldp_pacing*180)/100)+1,((ldp_pacing+1)*1*180)) as Pacing
, li_cost_type as `Cost Type`
, ord_total_budget as `Total Budget`
, li_is_automated
,li_target_server as Adserver
,li_del_pac_indicator as `DFP Report`
,li_submit_by
' )
->from('lineitems')
->innerJoin('orders','oid = li_order_id')
->leftJoin('advertisers','adv_id=ord_adv_id')
->leftJoin('sites','site_id=ord_site_id')
->leftJoin('products','prd_id=li_product')
->leftJoin('status_ref','status_id=li_status')
->leftJoin('users',"user_id='".$userid."'")
->leftJoin('user_role_profiles','urp_id=user_primary_role')
->leftJoin('lineitem_delivery_pacing','ldp_line_id = line_id')
->innerJoin("user_site_assoc","usc_site_id=ord_site_id and usc_userid='".$_SESSION['userId']."'")
->innerJoin("lineitem_revision_history", "lrh_lineitemid = line_id")
->where(" li_status not in ('Z','X') $cond")
->andWhere("li_order_id = oid")
->groupBy('line_id');
I am getting only the li_units_bought for one row. Not the sum of the rows having the same li_order_id.
Can someone tell me what I'm doing wrong?