2013-09-02 6 views
0

나는 다음과 같은 테이블이 있습니다 따옴표 quote_items old_products new_products MySQL의 조건 쿼리에 가입

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 

을 **을 수정 **

그런 경우 = 0 'old_kwh'특정 old_products위한 :3210

문제점이있다 I는 quote_items_input 테이블에서 kwh를 계산할 필요

여기서

quote_items_input.quote_item_id = quote_items.id 

quote_items_input table

SPE이 경우

,

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

그래서 '= 0 경우 old_products'.old_kwh cific quote의 경우, 해당 old_kwh를 합산 할 때 위의 방정식을 대신 대체해야합니다.

**

끝 는

어떻게이 위의 쿼리에 추가 할 수있는 **
EDIT? mysql을 사용하여 CASE 조건을 살펴 보았으나 지금까지 행운이 없었다.

어떤 도움을 감사

+0

내 대답을 제거 좋지 않을까. 필드 목록에서 사례를 사용하여 0으로 나누지 않습니다. –

+0

거기에 아무도 이것으로 나를 도울 수 있습니까?! 정말로 고투하고있는 Im, – mrcurious

+0

Im 완전히 여기에서 붙이게된다. 누군가 나를 위해 빛을 비춰 줄 수 있습니까? 이 쿼리가 가능합니까? – mrcurious

답변

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 
+0

답변 해 주셔서 감사합니다. 나는 CASE 섹션을 잘 모르겠다. q.old_kwh = 0이면 'SUM 방정식에서 old_kwh 대신 quote_items_input.input 값을 사용해야합니다. – mrcurious

+0

귀하의 의견에 따라 답변을 업데이트했습니다. 그것을 확인하십시오. – sarwar026

+0

Sarwar에게 감사 드려요. 잘못이지만 잘못된 값을 반환합니다. 내 잘못입니다. 검색어에 대해 언급하는 것을 잊어 버렸습니다. 일관성을위한 테이블 예제를 보여줄 필요가 있습니다. 어떻게 보여줄 수 있습니까? – mrcurious