帮助MySQL查询

时间:2011-08-21 13:53:28

标签: mysql sql

我有以下表结构:

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我必须使用select select,否则我会有错误的总和&事情变得一团糟,直到我达到一定程度,我忘记了我在做什么。

非常感谢任何帮助。

我当前的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 个答案:

答案 0 :(得分: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)-@ut AS sum_total,
    SUM((@st*b.vat)/100)-@uv 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