我用我的模式和一些测试数据创建了一个SQLFiddle(感谢Amadan!)。由于某种原因,计算的列在 SQLFiddle 中不起作用,但它们在我的 MYSQL Workbench 中运行良好。假设它们正常工作。
我的查询已经做到了这一点:
SELECT DISTINCT o.orderid,i.invoiceid,i.subinvoicenumber,stockingorderid AS oistockingorderid,
IF(stockingorderid > 0, 0, po.purchaseorderid) AS purchaseorderid,subponumber,po.paidvia,dropshipfee,i.taxstate,
COALESCE(
(SELECT mfrname
FROM cs_products.tblstockingorders so
WHERE so.stockingorderid=oistockingorderid),
po.mfrname)
AS source,
(i.shipping + i.surcharge +
(SELECT SUM(additionalshipping * quantity) AS additionalshipping
FROM cs_products.tblorderitems
WHERE invoiceid=i.invoiceid))
AS shipping,
CAST(IF(o.paymentmethod=2, CONCAT('Check: ', i.checknumber),o.paymentmethod) AS CHAR) AS invoicepaidvia,
COALESCE(
(SELECT (SUM(cost * quantity) * IF(so.mfrdiscount > 0, 1 - so.mfrdiscount, 1)) AS cost
FROM cs_products.tblorderitems oi
JOIN cs_products.tblallocations a ON oi.orderitemid=a.orderitemid
JOIN cs_products.tblstockingorders so ON a.stockingorderid=so.stockingorderid
WHERE a.stockingorderid=oistockingorderid),
(SELECT (SUM(cost * quantity) * IF(po.mfrdiscount > 0, 1 - po.mfrdiscount, 1)) AS cost
FROM cs_products.tblorderitems
WHERE purchaseorderid=po.purchaseorderid))
AS grosscost,
(SELECT SUM(price * quantity)
FROM cs_products.tblorderitems
WHERE invoiceid=i.invoiceid)
AS grossprice
FROM cs_products.tblorders o
JOIN cs_products.tblinvoices i ON o.orderid=i.orderid
#ordertype of 0 means the order came from the website
LEFT JOIN cs_products.tblpurchaseorders po ON o.orderid=po.orderid AND IF(o.ordertype<>0, subinvoicenumber=subponumber, subinvoicenumber=0 AND subponumber>=0)
LEFT JOIN cs_products.tblallocations a ON a.orderid=o.orderid
这让我到达那里的 95%。正如您所看到的,对于OrderId
1287,它显示了两条带有stockingorderid
s 的记录,而没有一条带有 a 的记录,purchaseorderid
即使采购订单已归属于 1287。我期望看到的缺失行类似于:
1287|276|0|NULL|194|0||0|0|'Quality Fabricators'|357.53|0|781.43|11917.70
同样,不要担心计算列,我只希望记录出现。我觉得我错过了最小的东西,但我不知道它是什么。
谢谢!
更新计算列不起作用的原因是因为使用了旧的订单项目数据。有机会我会更新的。