|id| VoucherNO| VoucherDate| +--+----------+------------+ |1 | 0001 | 28/9/2017 | |2 | 0010 | 27/9/2017 |
|id | ITEMID | QTYpurchased | voucher +---+--------+--------------+-------- |1 | 101 | 12 | 0001 |2 | 120 | 25 | 0001 |3 | 121 | 21 | 0014
|id| VoucherNO| VoucherDate| +--+----------+------------+ |1 | 0025 | 25/9/2017 | |2 | 0058 | 23/9/2017 |
|id | ITEMID | QTYpurchased | voucher +---+--------+--------------+-------- |1 | 101 | 8 | 0025 |2 | 120 | 5 | 0025 |3 | 121 | 10 | 0058
查询的目的是连接所有4个表以返回2个列 即。,
我试过的查询如下
SELECT
A.ITEMN,
A.ITEMNAME,
SUM(CAST(C.QUANTITY AS numeric(18,2))) - SUM(CAST(A.QTY AS numeric(18,2))) as QTY
FROM DETAILSALE A, SALESREPORT B, DETAILPURCHASES C, PURCHASEREPORT D
WHERE A.BARCODE = B.VOUCHERNO
AND C.BARCODE = D.VOUCHERNO
AND D.VOUCHERDATE=B.VOUCHERDATE
AND D.VOUCHERDATE BETWEEN '" & DATE1.Text & "' AND '" & DATE2.Text & "'
GROUP BY A.ITEMN,A.ITEMNAME
ORDER BY A.ITEMN ASC
| ITEMID | QTY | +--------+-----+ | 101 | 2 | | 120 | 10 | | 121 | 10 |
答案 0 :(得分:2)
首先聚合,然后才加入。我错过了您的说明中的产品表格以及表格说明中的名称和查询不匹配,因此您可能需要在我的查询中调整名称:
select
product.id,
product.name,
purchases.total,
sales.total
from product
left join
(
select itemid, sum(quantity) as total
from detail_purchase
where voucher in (select voucher from purchase where date between date '2017-09-01'
and date '2017-09-05')
group by itemid
) purchases on purchases.itemid = product.itemid
left join
(
select itemid, sum(quantity) as total
from detail_sale
where voucher in (select voucher from sale where date between date '2017-09-01'
and date '2017-09-05')
group by itemid
) sales on sales.itemid = product.itemid;
如果您只想要购买和/或销售的产品,请将外部连接更改为内部连接。