ALTER TABLE wmail_comm_offer_item ADD INDEX(comm_offer_id);
SELECT c.id, c.caption, COUNT(DISTINCT o.id) ordercount, COUNT(DISTINCT b.id) billcount, SUM(IF(b.status = '4', i.price_total, 0)) billsum
FROM wmail_company c
JOIN wmail_order o ON o.company_id = c.id
LEFT JOIN wmail_comm_bill b ON b.order_id = o.id
LEFT JOIN wmail_comm_bill_item i ON i.comm_bill_id = b.id
GROUP BY c.id, c.caption ORDER BY billsum DESC LIMIT 50
SELECT c.id, c.caption, COUNT(DISTINCT o.id) ordercount, COUNT(DISTINCT b.id) billcount, SUM(i.price_total) billsum
FROM wmail_company c
JOIN wmail_order o ON o.company_id = c.id
LEFT JOIN wmail_comm_bill b ON b.order_id = o.id
LEFT JOIN wmail_comm_bill_item i ON i.comm_bill_id = b.id AND b.status = 4
GROUP BY c.id, c.caption ORDER BY billsum DESC LIMIT 50
SELECT c.id, c.caption, COUNT(DISTINCT o.id) ordercount, COUNT(DISTINCT b.id) billcount, SUM(i.price_total) billsum
FROM wmail_company c
JOIN wmail_order o ON o.company_id = c.id
JOIN wmail_comm_bill b ON b.order_id = o.id
JOIN wmail_comm_bill_item i ON i.comm_bill_id = b.id AND b.status = 4
GROUP BY c.id, c.caption ORDER BY billsum DESC LIMIT 50
SELECT c.id, c.caption, COUNT(DISTINCT o.id) ordercount, COUNT(DISTINCT b.id) billcount, SUM(i.price_total) sum_price
FROM wmail_company c
JOIN wmail_order o ON o.company_id = c.id
JOIN wmail_comm_bill b ON b.order_id = o.id
JOIN wmail_comm_bill_item i ON i.comm_bill_id = b.id
GROUP BY c.id, c.caption ORDER BY billcount DESC LIMIT 0, 50
SELECT c.id, c.caption, COUNT(DISTINCT b.id) billcount, SUM(i.price_total) sum_price
FROM wmail_company c
JOIN wmail_order o ON o.company_id = c.id
JOIN wmail_comm_bill b ON b.order_id = o.id
JOIN wmail_comm_bill_item i ON i.comm_bill_id = b.id
GROUP BY c.id, c.caption ORDER BY billcount DESC LIMIT 0, 50