SELECT c.id, c.caption,
COUNT(DISTINCT o.id) ordercount,
COUNT(DISTINCT of.id) offercount,
SUM(ofi.price_total) offersum,
COUNT(DISTINCT b.id) billcount,
SUM(i.price_total) billsum
FROM wmail_company c
JOIN wmail_order o ON (o.company_id = c.id AND o.datetime > '2014-01-01')
LEFT JOIN wmail_comm_bill b ON (b.order_id = o.id AND b.status = '4')
LEFT JOIN wmail_comm_bill_item i ON (i.comm_bill_id = b.id)
LEFT JOIN wmail_comm_offer of ON (of.order_id = o.id)
LEFT JOIN wmail_comm_offer_item ofi ON (ofi.comm_offer_id = of.id)
GROUP BY c.id ORDER BY billsum DESC
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_offer b ON b.order_id = o.id
LEFT JOIN wmail_comm_offer_item i ON i.comm_offer_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
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 AND b.status = '4')
GROUP BY c.id, c.caption ORDER BY ordercount DESC LIMIT 50