我现在已经打破了这个问题了一段时间,所以我想我会在这里试一试。
我有以下表格:
quotes(id, quote_version_id, etc for brevity)
quote_versions(id, quote_id, etc)
v2_quote_payments(id, quote_id, amount, etc)
quote_product_items(quote_version_id, amount, discount, price, etc)
quote_freight_items(quote_version_id, amount, price, etc)
quote_service_items(quote_version_id, amount, price, etc)
引用有很多版本,但quote_version_id表示current_version
。我需要获得付款超过50%的报价(sum(v2_quote_payments.amount > (total_freights + total_products + total_services)
到目前为止,我有这个,但总和不一致(total_freights等),由于某种原因,我有总和,可能是由于不同的quote_versions
?
SELECT
quotes.id as quote_id,
quote_versions.id as quote_version,
sum(v2_op_payments.amount) as total_paid,
coalesce(sum(quote_product_items.amount * quote_product_items.price * (1 + (quote_product_items.discount/100))), 0) +
coalesce(sum(quote_service_items.amount * quote_service_items.price), 0) +
coalesce(sum(quote_freight_items.amount * quote_freight_items.price * (1 + (quote_freight_items.discount/100))), 0),
sum(quote_product_items.amount * quote_product_items.price * (1 + (quote_product_items.discount/100))) as total_prod,
sum(quote_service_items.amount * quote_service_items.price) as total_serv,
sum(quote_freight_items.amount * quote_freight_items.price * (1 + (quote_freight_items.discount/100))) as total_freight
FROM
`quotes`
INNER JOIN `v2_op_payments` ON `v2_op_payments`.`quote_id` = `quotes`.`id`
INNER JOIN `quote_versions` ON `quote_versions`.`quote_id` = `quotes`.`id`
INNER JOIN `v2_production_orders` ON `v2_production_orders`.`quote_id` = `quotes`.`id`
LEFT OUTER JOIN `quote_product_items` ON `quote_product_items`.`quote_version_id` = `quote_versions`.`id`
LEFT OUTER JOIN `quote_freight_items` ON `quote_freight_items`.`quote_version_id` = `quote_versions`.`id`
LEFT OUTER JOIN `quote_service_items` ON `quote_service_items`.`quote_version_id` = `quote_versions`.`id`
LEFT OUTER JOIN quote_cancellations ON quote_cancellations.quote_id = quotes.id
WHERE
`quote_cancellations`.`id` IS NULL
AND `quote_versions`.`approved` = 1
AND (quote_versions.id = quotes.quote_version_id)
GROUP BY
quotes.id
我这样做是为了检查每个报价的总和是否正确计算,然后继续。
其他条件仅检查报价是否已获批准,且报价中没有取消项目。
我在这里缺少什么?
谢谢,
修改
这是架构和查询的sqlfiddle:http://sqlfiddle.com/#!2/23ff06/1