mysql条件查询内连接

时间:2013-09-02 07:12:04

标签: mysql case inner-join

我有以下表格: 报价 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 table

在这种情况下,

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条件,但到目前为止没有运气。

任何帮助都会很棒 感谢

1 个答案:

答案 0 :(得分: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