Reputation: 775
I have two tables:
I wrote this query for getting data but I don't get data that I want. So please correct my query so that I get data that are in the image above.
SELECT
o.totalshippingfees,
o.totalamazonefees,
o.totalorderamount,
o.totalprofitloss,
o.totalprocessing_fees,
oi.totalproductexpense,
o.site
FROM (
SELECT
orderdate,
site,
sum(orders.shipping_fees) as totalshippingfees,
sum(orders.amazone_fees) as totalamazonefees,
sum(orders.totalAmount) as totalorderamount,
sum(orders.profit_loss) as totalprofitloss,
sum(orders.processing_fees) as totalprocessing_fees
FROM orders
group by site
) as o
JOIN (
SELECT
site,
sum(orderItemDetails.product_expense) as totalproductexpense,
sum(orders.shipping_fees) as totalshippingfees,
sum(orders.amazone_fees) as totalamazonefees,
sum(orders.totalAmount) as totalorderamount,
sum(orders.profit_loss) as totalprofitloss,
sum(orders.processing_fees) as totalprocessing_fees
from orders
LEFT JOIN orderItemDetails ON orders.id = orderItemDetails.orderId
group by site
) as oi
WHERE MONTH(o.orderdate) = '".$monthNo."' AND YEAR(o.orderdate)= '".$monthyear[1]."'
Upvotes: 0
Views: 60
Reputation: 17805
If I understand you correctly, you can use a simple group by site
on orders
and group by site
on orderItemDetails
and join them on site
.
select *
from (
select
sum(shipping_fees) as totalshippingfees,
sum(amazone_fees) as totalamazonefees,
sum(totalAmount) as totalorderamount,
sum(profit_loss) as totalprofitloss,
sum(processing_fees) as totalprocessing_fees,
site
from orders
group by site
) d1
join (
select
sum(product_expense) as totalproductexpense,
site
from orders o
left join orderItemDetails od
on o.id = od.orderId
group by site
) d2
on d1.site = d2.site
DB Fiddle: https://www.db-fiddle.com/f/dkpctq1XrzB7bfsrojaZHd/2
Update:
You can add a where
condition for date filtering as below:
select *
from (
select
sum(shipping_fees) as totalshippingfees,
sum(amazone_fees) as totalamazonefees,
sum(totalAmount) as totalorderamount,
sum(profit_loss) as totalprofitloss,
sum(processing_fees) as totalprocessing_fees,
site
from orders
where MONTH(orderdate) = 10 AND YEAR(orderdate) = 2019
group by site
) d1
join (
select
sum(product_expense) as totalproductexpense,
site
from orders o
left join orderItemDetails od
on o.id = od.orderId
where MONTH(o.orderdate) = 10 AND YEAR(o.orderdate) = 2019
group by o.site
) d2
on d1.site = d2.site
DB Fiddle: https://www.db-fiddle.com/f/kgZbS5U1oSgPAGX34URD22/0
Upvotes: 1