-1

我有一张销售订单和采购订单的表格。

销售订单

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

我想按日期显示总销售额和总购买量。

例如

 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";

请帮忙!谢谢!

4

2 回答 2

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
于 2012-10-27T02:54:41.080 回答
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

我不知道架构,所以你可以将“加入”更改为“正确加入”

于 2012-10-27T02:54:01.283 回答