sql没有正确计算总和

时间:2015-11-30 23:16:13

标签: sql sqlite

我有以下sql查询,它似乎是返回数据,但invoice_total(第4列)的总和未正确计算。目前,虽然我在购买文件中有大约50条记录,且重复的供应商ID,但我目前只有4条单独的供应商记录,其中包含invoice_total。返回的结果不是我放的。

SELECT p.orderID, s.supplier, SUM(IFNULL(pl.line_price,0)) AS total_order, SUM(IFNULL(p.invoice_total,0)) AS invoice_total  
  FROM purchase p 
  LEFT JOIN purchase_line pl 
  ON p.orderID = pl.orderID 
  LEFT JOIN supplier s 
  ON p.supplierID = s.supplierID 
  WHERE (p.date BETWEEN '2015-01-01' AND '2015-12-30')
  GROUP BY p.supplierID 
  ORDER BY p.supplierID ASC

表定义如下以及样本数据 购买

  orderID, date, supplierID, supplier_ref, invoice_total
  001, 2015-11-15, 1, abc, 11300000 
  002, 2015-11-15, 2, def, 23900000
  003, 2015-11-15, 3, ghi, 68265000
  004, 2015-11-15, 4, jkl, 31300000
  005, 2015-11-15, 5, lmn, [Null]

  purchase_line
  orderID, item_price, qty, line_price
  001,100000,50000, (that would be line_price*qty)
  001,200000,25000,
  001,300000,10000,
  002,400000,20000,
  003,300000,30000,
  004,200000,20000,

  supplier
  supplierID, supplier, address1, address2, zip
  1, Apple 
  2, Microsoft,
  3, Oracle
  4, SAP
  5, IBM

似乎为total_invoice字段返回的数据是。请记住,我只填充了invoice_total填充的一行数据。但是我在该字段中有许多与供应商1或供应商2相关联的Null记录。

  supplierID, invoice_total
  1, 700600000
  2, 95600000
  3, 136530000

1 个答案:

答案 0 :(得分:2)

invoice_totals的总和不正确,因为invoice_total值可以重复,因为每个订单可以在purchase_line中有多行。要解决此问题,您需要聚合两次,首先是supplieridorder,最后是supplierid

 SELECT supplierid ,
       SUM(total_order) AS total_order ,
       SUM(invoice_total) AS invoice_total
 FROM   ( SELECT    p.supplierID ,
                p.orderID ,
                SUM(IFNULL(pl.line_price, 0)) AS total_order ,
                IFNULL(p.invoice_total, 0) AS invoice_total
        FROM        purchase p
                LEFT JOIN purchase_line pl ON p.orderID = pl.orderID
                LEFT JOIN supplier s ON p.supplierID = s.supplierID
        WHERE   ( p.date BETWEEN '2015-01-01' AND '2015-12-30' )
        GROUP BY    p.supplierID ,
                p.orderID
       ) details
 GROUP BY   supplierID
 ORDER BY   supplierID ASC

只是为了澄清内部查询,对于Apple来说 IFNULL(p.invoice_total, 0)选择三个(重复)发票总额中的一个。您可以使用MIN(IFNULL(p.invoice_total, 0))MAX(IFNULL(p.invoice_total, 0))来实现相同的目标,因为invoice_totals都是重复的。