I am creating a report of Shops Order. SQL Query does work as expected.
It calulate the numbers of orders from each shop, the total cost of orders and our commission and the outstanding fields.
If the customer paid by Cash at the delivery, then it show OutstandingComm field
If the customer paid by Card from Online, then it show outstanding_shop field
SELECT T.ShopID, T.company, O.order_id, count(*) as NumOfOrders,
sum(O.shop_remaining) as ShopEarnings,
sum(O.comm_grandtotal) as OurComm,
SUM(CASE WHEN payment_method = 'PayCash' AND status = 1 THEN O.comm_grandtotal ELSE 0 END) as OutstandingComm,
SUM(CASE WHEN payment_method = 'PayCard' AND status = 1 THEN O.shop_remaining ELSE 0 END) as outstanding_shop
FROM Shops as T
JOIN orders O ON O.ShopID = T.ShopID
Group by ShopID
Can this SQL query could be improved or is there alternative better way?
Few things I can think of:
Here are some things to consider, try them if you feel like it, but be sure to time the effect of each change, it might not work or it might make things slower:
case whenlooks at a string (PayCash/PayCard). If you make that field a number, put an index on it and check the numeric value, it might run faster. The index might not get used though because it has a low cardinality.companynameand doesn’t need to do a full table read on table shops.status. Status has low cardinality, so an index will probably not be used, but if you partition, MySQL will only read from the status=1 version of the table, only do this when there are a lot ofstatus=0fields.shops.shopid.orders.shopid