title: MySQL Select problems
body: <p>Table #1: <strong>qa_returns_items</strong> <img src="https://i.stack.imgur.com/ySggc.png" alt="enter image description here"></p>
  
  <p>Table #2: <strong>qa_returns_residues</strong><img src="https://i.stack.imgur.com/5LjYV.png" alt="enter image description here"></p>
  
  <p>I have a long time trying to get this Result:</p>
  
  <pre><code>item_code -   item_quantity
  2         -   1
  3         -   2
  </code></pre>
  
  <hr>
  
  <p>IF qa_returns_items.item_code = qa_returns_residues.item_code AND status_code = 11 THEN</p>
  
  <blockquote>
    <p>item_quantity = qa_returns_items.item_quantity -
    qa_returns_residues.item_quantity</p>
  </blockquote>
  
  <p>ELSEIF qa_returns_items.item_code = qa_returns_residues.item_code AND status_code = 12 THEN </p>
  
  <blockquote>
    <p>item_quantity = qa_returns_items.item_quantity +
    qa_returns_residues.item_quantity</p>
  </blockquote>
  
  <p>ELSE</p>
  
  <pre><code>show diferendes
  </code></pre>
  
  <p>END IF</p>
  
  <p><strong>I tried this Query:</strong></p>
  
  <pre><code>select  SubQueryAlias.item_code, 
          item_quantity
  from    (
          select  
                  ri.item_code
          ,       case status_code
                  when 11 then ri.item_quantity - rr.item_quantity 
                  when 12 then ri.item_quantity + rr.item_quantity
                  end as item_quantity
          from    qa_returns_residues rr
          left join    qa_returns_items ri
          on      ri.item_code = rr.item_code
          WHERE ri.returnlog_code = 1
          ) as SubQueryAlias
  where   item_quantity &gt; 0 GROUP BY (item_code);
  </code></pre>
  
  <p><strong>The query returns this result:</strong></p>
  
  <pre><code>item_code -   item_quantity
  1         -   2
  2         -   2
  </code></pre>