0

我有以下表格:报价quote_items old_products new_products

quotes.id = quote_items.quote_id
old_products.id = quote_items.old_product_id
new_products.id = quote_items.new_product_id

我有这个查询可以计算出平均节省的百分比:

Select ROUND((sum(q.`old_kwh`) - sum(`p`.`new_kwh`))/sum(q.`old_kwh`)*100) as 
percentage_saved from quotes 
inner join quote_items
on quotes.id = `quote_items`.quote_id
INNER JOIN `new_products` p 
ON p.id = new_product_id
inner join old_products q
ON q.id = old_product_id

** 编辑 **

问题是这样的:对于某些 old_products,'old_kwh' = 0。在这种情况下:

我需要从 quote_items_input 表中计算 kwh,其中:

quote_items_input.quote_item_id = quote_items.id

quote_items_input 表

在这种情况下,

old_kwh = (old_Litre_measurement.input_value) * (Number of uses per day.input_value) * (avg shower time.input_value)
        = 20*2*10
        = 400

因此,如果特定报价的 'old_products'.old_kwh = 0,则在对特定 old_kwh 求和时,必须将上述等式替换为它的位置。

** 结束编辑 **

如何将其添加到上述查询中?我正在用 mysql 查看 CASE 条件,但到目前为止还没有运气。

任何帮助都会很棒谢谢

4

1 回答 1

0
SELECT
CASE q.old_kwh
    WHEN 0 THEN ROUND((sum(quote_items_input.input value) - sum(`p`.`new_kwh`))/sum(quote_items_input.input value)*100)
    ELSE ROUND((sum(q.`old_kwh`) - sum(`p`.`new_kwh`))/sum(q.`old_kwh`)*100)
END as percentage_saved 
FROM quotes 
INNER JOIN quote_items
on quotes.id = `quote_items`.quote_id
INNER JOIN quote_items_input
on quote_items_input.quote_item_id = quote_items.id
INNER JOIN `new_products` p 
ON p.id = new_product_id
INNER JOIN old_products q
ON q.id = old_product_id
于 2013-09-02T07:19:02.990 回答