我有一张销售订单和采购订单表。
销售订单
Date Amount
26/10 120
26/10 130
26/10 50
27/10 50
27/10 60
采购订单
Date Amount
26/10 200
26/10 300
26/10 100
27/10 100
27/10 100
我想按日期显示总销售额和总购买量。
E.g。
Date Total Sales Total Purchases
26/10 300 600
27/10 110 200
我的SQL查询是这样的,但它不起作用。
$query = "Select o.date, o.Amount AS Sales, p.date, p.Amount AS Purchases
From customerorder o
right join Purchaseorder p on o.date = p.date
order by o.date";
请帮忙!谢谢!
答案 0 :(得分:1)
SELECT COALESCE(o.date, p.date) date, Sales, Purchases
FROM (SELECT date, SUM(amount) Sales FROM CustomerOrder GROUP BY date) o
FULL JOIN (SELECT date, SUM(amount) Purchases FROM PurchaseOrder GROUP BY date) p
ON o.date = p.date
ORDER BY date
MySQL不支持FULL JOIN,因此专门针对MySQL,您可以使用
SELECT o.date, Sales, Purchases
FROM (SELECT date, SUM(amount) Sales FROM CustomerOrder GROUP BY date) o
LEFT JOIN (SELECT date, SUM(amount) Purchases FROM PurchaseOrder GROUP BY date) p
ON o.date = p.date
UNION ALL
SELECT date, NULL, SUM(amount) Purchases
FROM PurchaseOrder p2
WHERE NOT EXISTS (SELECT *
FROM CustomerOrder o2
WHERE o2.date = p2.date)
GROUP BY date
ORDER BY date
答案 1 :(得分:0)
select c.date,total_sales,total_purchase from
(select date,sum(amount) total_sales from customerorder group by date) c
join
(select date,sum(amount) total_purchase from purchaseorder group by date) p
on c.date=p.date
order by c.date
我不知道架构,所以你可以改变“加入”到“正确加入”