2011-08-21 59 views
1

我有以下表結構:幫助在MySQL查詢

Customers - Cust_Orders - Cust_Items - Cust_Payments - Drivers 
    id   id    id   id    id 
    company  cid   oid   oid   name 
       driver   price   amount 
       date   qty   date 
           vat 

我想要做的是顯示一個特定的驅動程序ID +所有未付訂單,爲除特定客戶的總和標誌着最後未支付的訂單是什麼已經選擇的訂單。

由於可能有不止一個cust_items &多個cust_payments我不得不使用從選擇否則我會錯的款項,直到我達到了一個點,我忘了我在做&事情變得混亂。

任何幫助將不勝感激。

我現在的SQL缺乏的最後一部分只(其它未支付的賬單金額總和):

SELECT `customers`.`company`, 
T1.*, 
ROUND(IFNULL(SUM(`cust_payments`.`amount`), 0), 2) AS `paid` 
FROM (
SELECT `cust_orders`.*, 
    ROUND(IFNULL(SUM(`cust_items`.`qty` * `cust_items`.`price`), 0), 2) AS `total`, 
    SUM((`cust_items`.`price` * `cust_items`.`qty` * `vat`)/100) AS `vat` 
    FROM `cust_orders` 
    LEFT JOIN `cust_items` ON `cust_orders`.`id` = `cust_items`.`oid` 
    GROUP BY `cust_orders`.`id` 
) `T1` 
LEFT JOIN `customers` ON `T1`.`cid` = `customers`.`id` 
LEFT JOIN `cust_payments` ON `T1`.`id` = `cust_payments`.`oid` 
WHERE `T1`.`driver` = ? GROUP BY `T1`.`id` HAVING (`T1`.`total` - `paid`) > ? 
ORDER BY `T1`.`id` DESC LIMIT 1 

回答

1

你可以嘗試

SELECT 
    x.id, 
    x.company, 
    y.id, 
    y.cid, 
    y.driver, 
    y.date, 
    @ut:=ROUND(SUM(z.qty*z.price),2) AS unpaid_total, 
    @uv:=SUM((@ut*z.vat)/100) AS unpaid_vat, 
    @st:=ROUND(SUM(b.qty*b.price),2)[email protected] AS sum_total, 
    SUM((@st*b.vat)/100)[email protected] AS sum_vat 
FROM Customers x 
INNER JOIN Cust_Orders y ON x.id=y.cid 
INNER JOIN Cust_Items z ON y.id=z.oid 
LEFT JOIN Cust_Orders a ON x.id=a.cid 
LEFT JOIN Cust_Items b ON a.id=b.oid 
WHERE 
    y.driver=? AND 
    NOT EXISTS (SELECT * FROM Cust_Payments WHERE oid=y.id) AND 
    NOT EXISTS (SELECT * FROM Cust_Payments WHERE oid=a.id) 
GROUP BY x.id,x.company, y.id, y.cid, y.driver, y.date 
+0

這看起來比我的例子更清晰,但它並不完全是什麼我期望。如我應該結束了**一個未付順序**每個客戶+其他未結算訂貨該客戶的總和(除所顯示的順序)。我會盡量根據您的例子我的工作來重建和明天早上發佈了回去。 – Frank

+0

簡單的我忘了,包括客戶'id'? – rabudde