2017-08-16 101 views
-1

傢伙,我有這樣的事情:CASE WHEN,選擇MYSQL

select t1.milestone_id, sum(t2.value)/count(t2.value) as value2, value3 
from (
      SELECT milestone_id, SUM(value) value , CASE WHEN (status !='done') THEN (value ='0') ELSE value END as value3 
      FROM project_has_tasks 
      WHERE project_id='52' and milestone_id !=0 
      GROUP BY milestone_id 
     ) t1 
join (
      SELECT milestone_id, SUM(value) value 
      FROM project_has_tasks 
      WHERE project_id='52' and milestone_id !=0 
      GROUP BY milestone_id 
     ) t2 
on  t1.milestone_id >= t2.milestone_id 
group by t1.milestone_id 
order by t1.milestone_id asc 

得到這個: enter image description here

可以請你幫我弄這些價值3爲values2除了0 這種像這樣:

enter image description here

感謝您的任何建議。

回答

0

修改您的第一行:

SELECT t1.milestone_id, sum(t2.value)/count(t2.value) as value2, IF(value3=0, sum(t2.value)/count(t2.value), value3) as value3 

IF語句的工作原理如下(see the doc)

IF(<expression>, <expression is true>, <expression is false>) 

如果表達式不爲NULL,而不是0它被認爲是真實的。

+0

#1054 - 在 '字段列表' 未知列 '值' –

+0

忘記值2計算 – BlobbyBob

+0

如果我將使用: SELECT t1.milestone_id,SUM(t2.value )/ count(t2.value)as value2,IF(value3 = 0,sum(t2.value)/ count(t2.value),value3)as value3 then value3與value2相同 –

0

感謝您的建議。下面的代碼工作不錯:)

select t1.milestone_id, sum(t2.value)/count(t2.value) as value2, IF(value3 !='0', sum(t2.value)/count(t2.value), value3)as value3 
    from (
       SELECT milestone_id, SUM(value) value , CASE WHEN (status !='done') THEN (value ='0') ELSE value END as value3 
       FROM project_has_tasks 
       WHERE project_id='52' and milestone_id !=0 
       GROUP BY milestone_id 
      ) t1 
    join (
       SELECT milestone_id, SUM(value) value 
       FROM project_has_tasks 
       WHERE project_id='52' and milestone_id !=0 
       GROUP BY milestone_id 
      ) t2 
    on  t1.milestone_id >= t2.milestone_id 
    group by t1.milestone_id 
    order by t1.milestone_id asc