来自两个表的sql sum

时间:2015-04-22 22:28:41

标签: sql sqlite

我在sqlite中有两个单独的表,称为发票和购买,我使用下面的查询来检索与项目7相关的所有发票和购买的总和。事情是发票有三个记录和在sql中返回的值是正确的,但购买等价物是错误的,因为只有一条记录,但返回的值乘以三。

SELECT sum(invoice.invoice_net) As Sales, sum(purchase.total_order) As Purchases
FROM invoice
LEFT JOIN purchase
ON purchase.projectID=invoice.projectID
WHERE invoice.projectID=7

如何加入这两个语句,以便正确返回数据。我个人都知道他们工作得很好。我已尝试过Union,但这会将数据放入一列。

SELECT sum(invoice.invoice_net) As Sales
FROM invoice
WHERE projectID=7

SELECT sum(purchase.order_total) As Purchases
FROM purchase
WHERE projectID=7

1 个答案:

答案 0 :(得分:1)

一个选项是使用子查询image = cv2.imread(args["image"]) r = 150.0 / image.shape[1] dim = (150, int(image.shape[0] * r)) resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) lower_white = np.array([220, 220, 220], dtype=np.uint8) upper_white = np.array([255, 255, 255], dtype=np.uint8) mask = cv2.inRange(resized, lower_white, upper_white) # could also use threshold res = cv2.bitwise_not(resized, resized, mask) cv2.imshow('res', res) # gives black background 结果,然后执行sum

outer join

另一个选择是使用相关子查询:

SELECT invoice.Sales, purchase.Purchases
FROM (
    SELECT sum(invoice.invoice_net) As Sales, projectID
    FROM invoice
    GROUP BY projectID
) invoice LEFT JOIN (
    SELECT sum(total_order) As Purchases, projectID
    FROM purchase 
    GROUP BY projectID
) purchase ON purchase.projectID=invoice.projectID
WHERE invoice.projectID=7